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

import requests
from pathlib import Path
import sys

# UTF-8 safety
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 který sledujeme


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


# === QUERY ===

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


def run_query(request_id, token):
    payload = {
        "operationName": "ClinicRequestNotes_Get",
        "query": QUERY,
        "variables": {"patientRequestId": request_id},
    }

    headers = {
        "Authorization": f"Bearer {token}",
        "Content-Type": "application/json",
        "Accept": "application/json",
    }

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

    return r.json()


def main():
    token = read_token(TOKEN_PATH)

    print(f"🔍 Čtu interní klinické poznámky k požadavku {REQUEST_ID} ...\n")

    data = run_query(REQUEST_ID, token)

    notes = data.get("data", {}).get("notes", [])
    if not notes:
        print("📭 Žádné klinické poznámky nejsou uložené.")
        return

    print(f"📌 Nalezeno {len(notes)} poznámek:\n")

    for n in notes:
        print("──────────────────────────────")
        print(f"🆔 ID: {n['id']}")
        print(f"👤 Vytvořil: {n['createdBy']['surname']} {n['createdBy']['name']}")
        print(f"📅 createdAt: {n['createdAt']}")
        print(f"🕒 updatedAt: {n['updatedAt']}")
        print("📝 Obsah:")
        print(n['content'])
        print("")


if __name__ == "__main__":
    main()
