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

from playwright.sync_api import sync_playwright
import json, os, time

STATE_FILE = "../medevio_storage.json"
GRAPHQL_LOG = f"graphql_capture_{int(time.time())}.jsonl"

with sync_playwright() as pw:
    browser = pw.chromium.launch(headless=False, slow_mo=200)
    context = browser.new_context(storage_state=STATE_FILE)
    page = context.new_page()

    def log_graphql(req):
        if "graphql" in req.url and req.method == "POST":
            try:
                body = req.post_data or ""
                data = json.loads(body)
                with open(GRAPHQL_LOG, "a", encoding="utf-8") as f:
                    f.write(json.dumps(data, ensure_ascii=False) + "\n")
                print(f"📡 {data.get('operationName')} saved")
            except Exception:
                pass

    page.on("request", log_graphql)

    print("🔗 Opening Medevio main page...")
    page.goto("https://my.medevio.cz/mudr-buzalkova/klinika/kalendar/agenda-dne/"
              "?kalendar=144c4e12-347c-49ca-9ec0-8ca965a4470d", wait_until="networkidle")

    print("\n👉 Click various items in Medevio (calendar, reservations, requests, etc.).")
    print("   Every GraphQL call will be saved to", GRAPHQL_LOG)
    print("   Press Ctrl+C or close the browser when done.\n")

    try:
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        browser.close()
        print(f"\n✅ Finished — GraphQL calls saved to {GRAPHQL_LOG}")
