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

import json
from pathlib import Path
import requests

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

GRAPHQL_QUERY = r"""
query ClinicRequestGrid_ListPatientRequestsForClinic2(
  $clinicSlug: String!,
  $queueId: String,
  $queueAssignment: QueueAssignmentFilter!,
  $pageInfo: PageInfo!,
  $locale: Locale!
) {
  requestsResponse: listPatientRequestsForClinic2(
    clinicSlug: $clinicSlug
    queueId: $queueId
    queueAssignment: $queueAssignment
    pageInfo: $pageInfo
  ) {
    count
    patientRequests {
      id
      createdAt
      doneAt
      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",
    }

    # 👇 state zcela vynechán
    variables = {
        "clinicSlug": CLINIC_SLUG,
        "queueId": None,
        "queueAssignment": "ANY",
        "pageInfo": {"first": 10, "offset": 0},
        "locale": "cs",
    }

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

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

    try:
        data = r.json()
        print("=== JSON response ===")
        print(json.dumps(data, indent=2, ensure_ascii=False))
    except Exception as e:
        print("❌ Failed to parse JSON:", e)
        print("Raw text:\n", r.text)

if __name__ == "__main__":
    main()
