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

"""
Open the Medevio daily agenda calendar,
inspect the rendered HTML, and probe JS memory
to see what data is exposed.
"""

from playwright.sync_api import sync_playwright

STATE_FILE = "medevio_storage.json"
AGENDA_URL = (
    "https://my.medevio.cz/mudr-buzalkova/klinika/kalendar/agenda-dne/"
    "?kalendar=144c4e12-347c-49ca-9ec0-8ca965a4470d&datum=2025-10-17"
)

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

        print("🔗 Opening agenda-day calendar...")
        page.goto(AGENDA_URL, wait_until="networkidle", timeout=90_000)

        # -------- Check login --------
        body = (page.text_content("body") or "").lower()
        if any(x in body for x in ["přihlášení", "přihlásit", "sign in", "login"]):
            raise SystemExit("❌ Not logged in – refresh medevio_storage.json.")

        # -------- Wait for appointments to render --------
        page.wait_for_timeout(4000)

        # -------- Dump a few appointment blocks --------
        blocks = page.locator("div.rbc-event-inner-content, div[data-testid='Reservation']").evaluate_all(
            "(els) => els.map(e => e.outerHTML)"
        )
        print(f"\n✅ Found {len(blocks)} appointment blocks. Showing first 3:\n")
        for snippet in blocks[:3]:
            print(snippet)
            print("-" * 80)

        # -------- Explore window memory --------
        print("\n🔍 Inspecting global JS variables...")
        keys = page.evaluate("Object.keys(window)")
        interesting = [k for k in keys if any(w in k.lower() for w in ["mede", "cal", "react", "state", "reserv"])]
        print("Interesting keys:", interesting[:20])

        for candidate in [
            "window.__INITIAL_STATE__",
            "window.__INITIAL_DATA__",
            "window.__REACT_DEVTOOLS_GLOBAL_HOOK__",
            "window.medevioCalendar",
            "window.calendarStore",
            "window.reduxStore",
            "window.reactProps",
        ]:
            try:
                data = page.evaluate(f"JSON.stringify({candidate}, null, 2)")
                if data and len(data) > 200:
                    print(f"\n===== {candidate} =====\n{data[:1000]}...\n")
            except Exception:
                pass

        # -------- Optionally: listen for network requests while you click --------
        def log_request(req):
            url = req.url
            if any(x in url for x in ["pozadavek", "request", "api"]):
                print("📡", url)

        page.on("request", log_request)
        print("\n👉 Now click manually on a few agenda items to open their detail cards.")
        print("   Any backend calls will appear below.\n")

        page.wait_for_timeout(40000)  # give yourself ~40s to click around
        browser.close()

if __name__ == "__main__":
    main()
