#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import requests
from pathlib import Path
import sys

# UTF-8 handling
try:
    sys.stdout.reconfigure(encoding='utf-8')
except:
    pass

# === CONFIG ===

TOKEN_PATH = Path(__file__).resolve().parent.parent / "token.txt"
GRAPHQL_URL = "https://api.medevio.cz/graphql"

REQUEST_ID = "e17536c4-ed22-4242-ada5-d03713e0b7ac"   # požadavek
NOTE_PREPEND_TEXT = "🔥 NOVÝ TESTOVACÍ ŘÁDEK\n"           # text, který se přidá NA ZAČÁTEK


# === Helpers ===

def read_token(p: Path) -> str:
    t = p.read_text().strip()
    if t.startswith("Bearer "):
        return t.split(" ", 1)[1]
    return t


# === Queries ===

QUERY_GET_NOTES = r"""
query ClinicRequestNotes_Get($patientRequestId: String!) {
  notes: getClinicPatientRequestNotes(requestId: $patientRequestId) {
    id
    content
    createdAt
    updatedAt
    createdBy {
      id
      name
      surname
    }
  }
}
"""

MUTATION_UPDATE_NOTE = r"""
mutation ClinicRequestNotes_Update($noteInput: UpdateClinicPatientRequestNoteInput!) {
  updateClinicPatientRequestNote(noteInput: $noteInput) {
    id
  }
}
"""


# === Core functions ===

def gql(query, variables, token):
    headers = {
        "Authorization": f"Bearer {token}",
        "Content-Type": "application/json",
        "Accept": "application/json",
    }
    payload = {"query": query, "variables": variables}

    r = requests.post(GRAPHQL_URL, json=payload, headers=headers)
    r.raise_for_status()
    return r.json()


def get_internal_note(request_id, token):
    data = gql(QUERY_GET_NOTES, {"patientRequestId": request_id}, token)
    notes = data.get("data", {}).get("notes", [])
    return notes[0] if notes else None


def update_internal_note(note_id, new_content, token):
    variables = {"noteInput": {"id": note_id, "content": new_content}}
    return gql(MUTATION_UPDATE_NOTE, variables, token)


# === MAIN ===

def main():
    token = read_token(TOKEN_PATH)

    print(f"🔍 Načítám interní poznámku pro požadavek {REQUEST_ID}...\n")

    note = get_internal_note(REQUEST_ID, token)
    if not note:
        print("❌ Nebyla nalezena žádná interní klinická poznámka!")
        return

    note_id = note["id"]
    old_content = note["content"] or ""

    print("📄 Původní obsah:")
    print(old_content)
    print("────────────────────────────\n")

    # ===============================
    #    PREPEND new text
    # ===============================
    new_content = NOTE_PREPEND_TEXT + old_content

    print("📝 Nový obsah který odešlu:")
    print(new_content)
    print("────────────────────────────\n")

    # UPDATE
    result = update_internal_note(note_id, new_content, token)

    print(f"✅ Hotovo! Poznámka {note_id} aktualizována.")
    print(result)


if __name__ == "__main__":
    main()
