#!/usr/bin/env python3
"""ApEn mouse — 2-test with synthetic input (since demo only has 'start-real' mode)."""
import asyncio, subprocess, time, os, glob
from playwright.async_api import async_playwright

PORT = 9350
CHROME = "/usr/bin/google-chrome"
if not os.path.exists(CHROME):
    cands = glob.glob("/home/huxley/.cache/ms-playwright/chromium_headless_shell-*/chrome-headless-shell-linux64/chrome-headless-shell")
    if cands: CHROME = cands[0]


async def run(p, use_cdp):
    if use_cdp:
        import uuid
        udir = f"/tmp/apen_cdp_{uuid.uuid4().hex[:8]}"
        proc = subprocess.Popen([CHROME, "--headless=new", "--no-sandbox", "--disable-gpu",
                                  f"--remote-debugging-port={PORT}", f"--user-data-dir={udir}",
                                  "about:blank"],
                                 stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
        time.sleep(3)
        try:
            browser = await p.chromium.connect_over_cdp(f"http://localhost:{PORT}")
            ctx = browser.contexts[0] if browser.contexts else await browser.new_context()
            page = ctx.pages[0] if ctx.pages else await ctx.new_page()
        except Exception as e:
            proc.terminate()
            return {"error": str(e)}
    else:
        browser = await p.chromium.launch(headless=True, args=["--no-sandbox", "--disable-setuid-sandbox", "--disable-dev-shm-usage"])
        page = await (await browser.new_context()).new_page()

    try:
        await page.goto("http://127.0.0.1:3457/spikes/apen-mouse/demo.html", wait_until="networkidle", timeout=15000)
        # Get the zone bounds
        bounds = await page.evaluate("""() => {
            const z = document.getElementById('mouse-zone');
            const r = z.getBoundingClientRect();
            return {x: r.x, y: r.y, w: r.width, h: r.height};
        }""")
        print(f"  Zone bounds: {bounds}")
        await page.click("#start-real")
        # 60 clustered synthetic moves inside the zone
        for i in range(60):
            x = bounds['x'] + bounds['w']/2 + (i * 5) % 100 - 50
            y = bounds['y'] + bounds['h']/2 + (i * 3) % 80 - 40
            await page.mouse.move(x, y)
            await page.wait_for_timeout(100)
        # Wait for the 8s collection + auto-analyze
        await page.wait_for_timeout(2500)
        # Get verdict
        verdict_text = await page.inner_text("#verdict-area")
        status_text = await page.inner_text("#status-area")
        await browser.close()
    finally:
        if use_cdp:
            proc.terminate()
            time.sleep(1)
            if proc.poll() is None: proc.kill()
    return {"verdict": verdict_text, "status": status_text}


async def main():
    async with async_playwright() as p:
        v = await run(p, False)
        c = await run(p, True)
    print("=" * 60)
    print("ApEn Mouse — 2-test")
    print("=" * 60)
    print(f"Vanilla verdict: {v.get('verdict', '?')[:500]}")
    print(f"CDP verdict:     {c.get('verdict', '?')[:500]}")
    print(f"Vanilla status:  {v.get('status', '?')[:300]}")
    print(f"CDP status:      {c.get('status', '?')[:300]}")


asyncio.run(main())
