"""
Read what the panel-manager ALREADY says about each panel's state.
No new code — just inspect the DOM that addPanel() already produced.
"""
import asyncio
import json
import sys
from pathlib import Path
from playwright.async_api import async_playwright


PANELS = ["pages", "users", "settings", "monitor", "audit", "deploy", "ai", "ai2", "mig"]
URL = "http://localhost:8765/demo/admin-launcher-test.html"
OUT_DIR = Path("/workspace/freshvibe-cms/aux-tests/launcher/state-audit")
OUT_DIR.mkdir(parents=True, exist_ok=True)


async def main():
    async with async_playwright() as p:
        browser = await p.chromium.launch(
            headless=True,
            executable_path="/root/.cache/ms-playwright/chromium-1223/chrome-linux/chrome",
            args=["--no-sandbox", "--disable-setuid-sandbox", "--disable-gpu"],
            timeout=10000,
        )
        context = await browser.new_context(viewport={"width": 1400, "height": 1400})
        page = await context.new_page()
        page_errors = []
        page.on("pageerror", lambda e: page_errors.append(str(e)))
        page.on("console", lambda m: page_errors.append(f"console.{m.type}: {m.text}") if m.type == "error" and "favicon" not in m.text else None)

        await page.goto(URL, wait_until="networkidle", timeout=10000)
        await page.wait_for_timeout(500)

        buttons = await page.query_selector_all("#buttonGrid .btn")
        assert len(buttons) >= 9

        findings = []
        for i, pid in enumerate(PANELS):
            # Clean slate between panels
            await page.evaluate("""() => {
                document.querySelectorAll('[data-panel-id]').forEach(p => p.remove());
            }""")
            await page.wait_for_timeout(100)
            await buttons[i].click()
            await page.wait_for_timeout(300)

            # Read what addPanel() already wrote into the DOM
            info = await page.evaluate("""(pid) => {
                const p = document.querySelector('[data-panel-id]');
                if (!p) return { found: false };
                const header = p.querySelector('.fvcms-pm-header');
                const titleSpan = p.querySelector('.fvcms-pm-title');
                const controls = p.querySelector('.fvcms-pm-controls');
                const squeeze = p.querySelector('.fvcms-pm-squeeze');
                const collapse = p.querySelector('.fvcms-pm-collapse');
                const detach = p.querySelector('.fvcms-pm-detach');
                const close = p.querySelector('.fvcms-pm-close');
                const grip = p.querySelector('.fvcms-pm-grip');
                const resize = p.querySelector('.fvcms-pm-resize');
                const body = p.querySelector('.fvcms-pm-body');

                function elInfo(el) {
                    if (!el) return { exists: false };
                    const r = el.getBoundingClientRect();
                    const c = getComputedStyle(el);
                    return {
                        exists: true,
                        x: r.x, y: r.y, w: r.width, h: r.height,
                        display: c.display, visibility: c.visibility,
                        cursor: c.cursor,
                    };
                }
                const headerCS = header ? getComputedStyle(header) : null;
                return {
                    found: true,
                    state: p.getAttribute('data-state'),
                    dockEdge: p.getAttribute('data-dock-edge'),
                    overlayMode: p.getAttribute('data-overlay-mode'),
                    panel: { x: p.getBoundingClientRect().x, y: p.getBoundingClientRect().y, w: p.getBoundingClientRect().width, h: p.getBoundingClientRect().height },
                    header: {
                        exists: !!header,
                        rect: header ? { w: header.getBoundingClientRect().width, h: header.getBoundingClientRect().height } : null,
                        bg: headerCS ? headerCS.backgroundColor : null,
                        color: headerCS ? headerCS.color : null,
                        titleText: titleSpan ? titleSpan.textContent : null,
                    },
                    buttons: {
                        squeeze: elInfo(squeeze),
                        collapse: elInfo(collapse),
                        detach: elInfo(detach),
                        close: elInfo(close),
                    },
                    resize: elInfo(resize),
                    grip: elInfo(grip),
                };
            }""", pid)

            screenshot = str(OUT_DIR / f"{pid}-state.png")
            await page.evaluate("""() => {
                const p = document.querySelector('[data-panel-id]');
                if (p) {
                    p.style.zIndex = '99999';
                    p.style.left = '500px';
                    p.style.top = '60px';
                }
            }""")
            await page.wait_for_timeout(150)
            await page.screenshot(path=screenshot, full_page=False)
            info["pid"] = pid
            info["screenshot"] = screenshot
            findings.append(info)

        await browser.close()

    out_file = OUT_DIR / "findings.json"
    out_file.write_text(json.dumps({"findings": findings, "page_errors": page_errors}, indent=2))
    print(f"\n— State audit complete. {len(findings)} panels. {out_file}")

    print("\n" + "="*70)
    print("RAW STATE")
    print("="*70)
    for f in findings:
        if not f["found"]:
            print(f"  ✗ {f['pid']}: NOT FOUND")
            continue
        print(f"  {f['pid']}: state={f['state']!r} edge={f['dockEdge']!r} overlay={f['overlayMode']!r}")
        print(f"      panel rect: {f['panel']['w']:.0f}x{f['panel']['h']:.0f} @ ({f['panel']['x']:.0f},{f['panel']['y']:.0f})")
        print(f"      header: bg={f['header']['bg']} title={f['header']['titleText']!r}")
        for btn_name in ("squeeze", "collapse", "detach", "close"):
            b = f["buttons"][btn_name]
            if b["exists"]:
                print(f"      {btn_name}: {b['w']:.0f}x{b['h']:.0f} visible={b['visibility']!r} cursor={b['cursor']!r}")
            else:
                print(f"      {btn_name}: MISSING")
        r = f["resize"]
        g = f["grip"]
        if r["exists"]:
            print(f"      resize handle: {r['w']:.0f}x{r['h']:.0f} @ ({r['x']:.0f},{r['y']:.0f})")
        else:
            print(f"      resize handle: NONE")
        if g["exists"]:
            print(f"      grip handle: {g['w']:.0f}x{g['h']:.0f}")
        else:
            print(f"      grip handle: NONE")


if __name__ == "__main__":
    asyncio.run(main())
