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

import json
from pathlib import Path
import requests  # 👈 this is new

# --- Settings ----------------------------------------------------
TOKEN_PATH = Path(__file__).resolve().parent.parent / "token.txt"
CLINIC_SLUG = "mudr-buzalkova"
SHOW_FULL_TOKEN = False          # set True if you want to print the full token
# -----------------------------------------------------------------

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
    createdAt
    dueDate
    displayTitle(locale: $locale)
    doneAt
    removedAt
    priority
    evaluationResult(locale: $locale) { fields { name value } }
    clinicId
    extendedPatient {
      id
      identificationNumber
      kind
      name
      surname
      status
      isUnknownPatient
    }
    lastMessage { id text createdAt }
    queue { id name }
    reservations { id canceledAt done start }
    tags(onlyImportant: true) { id name color icon }
    priceWhenCreated
    currencyWhenCreated
  }
}
"""

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,
    }

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

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

if __name__ == "__main__":
    main()
