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

"""
Query Medevio for the full agenda of 17 Oct 2025 and print raw API response.
"""

import json
import requests

GRAPHQL_URL = "https://api.medevio.cz/graphql"

CALENDAR_ID = "144c4e12-347c-49ca-9ec0-8ca965a4470d"
CLINIC_SLUG = "mudr-buzalkova"

def load_gateway_token(storage_path="medevio_storage.json"):
    """Return Medevio gateway-access-token from saved Playwright storage."""
    import json
    from pathlib import Path

    path = Path(storage_path)
    if not path.exists():
        raise SystemExit(f"❌ Storage file not found: {path}")

    with path.open("r", encoding="utf-8") as f:
        state = json.load(f)

    token = next(
        (c["value"] for c in state["cookies"]
         if c["name"] == "gateway-access-token"), None
    )

    if not token:
        raise SystemExit("❌ gateway-access-token not found in storage file.")

    return token

gateway_token = load_gateway_token()

headers = {
    "content-type": "application/json",
    "origin": "https://my.medevio.cz",
    "referer": "https://my.medevio.cz/",
    "authorization": f"Bearer {gateway_token}",
}

payload = {
    "operationName": "ClinicAgenda_ListClinicReservations",
    "variables": {
        "calendarIds": [CALENDAR_ID],
        "clinicSlug": CLINIC_SLUG,
        "since": "2025-10-16T22:00:00.000Z",
        "until": "2025-10-17T21:59:59.999Z",
        "locale": "cs",
        "emptyCalendarIds": False,
    },
    "query": """query ClinicAgenda_ListClinicReservations(
      $calendarIds: [UUID!],
      $clinicSlug: String!,
      $locale: Locale!,
      $since: DateTime!,
      $until: DateTime!,
      $emptyCalendarIds: Boolean!
    ) {
      reservations: listClinicReservations(
        clinicSlug: $clinicSlug,
        calendarIds: $calendarIds,
        since: $since,
        until: $until
      ) @skip(if: $emptyCalendarIds) {
        id
        start
        end
        note
        done
        color
        request {
          id
          displayTitle(locale: $locale)
          extendedPatient {
            name
            surname
            dob
            insuranceCompanyObject { shortName }
          }
        }
      }
    }""",
}

print("📡 Querying Medevio API for agenda...")
r = requests.post(GRAPHQL_URL, headers=headers, data=json.dumps(payload))
print("Status:", r.status_code)

try:
    data = r.json()
    print(json.dumps(data, indent=2, ensure_ascii=False))
except Exception as e:
    print("❌ Could not parse JSON:", e)
    print(r.text)
