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

import json
from pathlib import Path
import requests

# --- Settings ----------------------------------------------------
TOKEN_PATH = Path(__file__).resolve().parent.parent / "token.txt"
CLINIC_SLUG = "mudr-buzalkova"
# -----------------------------------------------------------------

GRAPHQL_QUERY = r"""
query ClinicLegacyRequestList_ListPatientRequestsForClinic(
  $clinicSlug: String!,
  $queueId: String,
  $queueAssignment: QueueAssignmentFilter!,
  $state: PatientRequestState,
  $pageInfo: PageInfo!,
  $locale: Locale!
) {
  requests: listPatientRequestsForClinic(
    clinicSlug: $clinicSlug,
    queueId: $queueId,
    queueAssignment: $queueAssignment,
    state: $state,
    pageInfo: $pageInfo
  ) {
    id
    displayTitle(locale: $locale)
    extendedPatient {
      name
      surname
      identificationNumber
    }
  }
}
"""

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

def main():
    token = read_token(TOKEN_PATH)

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

    variables = {
        "clinicSlug": CLINIC_SLUG,
        "queueId": None,
        "queueAssignment": "ANY",
        "state": "ACTIVE",                 # pending / nevyřízené
        "pageInfo": {"first": 30, "offset": 0},
        "locale": "cs",
    }

    payload = {
        "operationName": "ClinicLegacyRequestList_ListPatientRequestsForClinic",
        "query": GRAPHQL_QUERY,
        "variables": variables,
    }

    url = "https://api.medevio.cz/graphql"
    print("📡 Querying Medevio GraphQL API...\n")
    r = requests.post(url, json=payload, headers=headers)
    print(f"HTTP status: {r.status_code}\n")

    # --- Parse JSON safely
    try:
        data = r.json()
    except Exception as e:
        print("❌ Failed to decode JSON:", e)
        print("Raw text:\n", r.text)
        return

    requests_data = data.get("data", {}).get("requests", [])
    if not requests_data:
        print("⚠️ No requests found or invalid response.")
        return

    print(f"📋 Found {len(requests_data)} active requests:\n")
    for req in requests_data:
        patient = req.get("extendedPatient", {})
        print(f"- {patient.get('surname','')} {patient.get('name','')} "
              f"({patient.get('identificationNumber','')}) "
              f"→ {req.get('displayTitle','')} [ID: {req.get('id')}]")

if __name__ == "__main__":
    main()
