#!/usr/bin/env python3
"""CMS shell smoke test. Loads /admin/ via Playwright and reports console errors."""
import asyncio
import subprocess
import time
from pathlib import Path
from playwright.async_api import async_playwright

DIST = Path("/workspace/projects/oscar-web/dist")
PORT = 18804


def serve():
    # Try to kill any old server (best-effort, ignore failure)
    try:
        subprocess.run(["pkill", "-f", f"http.server {PORT}"], capture_output=True, timeout=2)
    except Exception:
        pass
    time.sleep(0.5)
    proc = subprocess.Popen(
        ["python3", "-m", "http.server", str(PORT), "--bind", "127.0.0.1", "--directory", str(DIST)],
        stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
    )
    time.sleep(2)
    return proc


async def main():
    proc = serve()
    console_msgs = []
    page_errors = []
    failed_requests = []
    try:
        async with async_playwright() as pw:
            browser = await pw.chromium.launch(
                headless=True,
                executable_path="/root/.cache/ms-playwright/chromium-1223/chrome-linux/chrome",
                args=["--no-sandbox"],
            )
            ctx = await browser.new_context(viewport={"width": 1280, "height": 800})
            page = await ctx.new_page()
            page.on("console", lambda msg: console_msgs.append(f"[{msg.type}] {msg.text}"))
            page.on("pageerror", lambda err: page_errors.append(str(err)))
            page.on("requestfailed", lambda req: failed_requests.append(f"{req.method} {req.url} :: {req.failure}"))

            print("--- Navigating to /admin/ ---")
            await page.goto(f"http://127.0.0.1:{PORT}/admin/", wait_until="networkidle", timeout=30)
            await page.wait_for_timeout(2000)

            title = await page.title()
            body_html = await page.evaluate("document.body.innerHTML.substring(0, 2000)")
            has_cms_app = await page.evaluate("!!document.getElementById('cms-app')")
            cms_app_inner = await page.evaluate("document.getElementById('cms-app')?.innerHTML?.length || 0")

            print(f"  title: {title}")
            print(f"  #cms-app exists: {has_cms_app}")
            print(f"  #cms-app content length: {cms_app_inner} chars")

            # Screenshot
            shot = DIST.parent / "metrics" / "admin-shell-load.png"
            shot.parent.mkdir(parents=True, exist_ok=True)
            await page.screenshot(path=str(shot), full_page=True)
            print(f"  screenshot: {shot}")

            print(f"\n--- Console messages ({len(console_msgs)}) ---")
            for m in console_msgs[:20]:
                print(f"  {m}")

            print(f"\n--- Page errors ({len(page_errors)}) ---")
            for e in page_errors[:10]:
                print(f"  {e}")

            print(f"\n--- Failed requests ({len(failed_requests)}) ---")
            for r in failed_requests[:10]:
                print(f"  {r}")

            await browser.close()
    finally:
        proc.terminate()
        try: proc.wait(timeout=3)
        except: proc.kill()

    return len(page_errors), len(failed_requests)


if __name__ == "__main__":
    errs, failed = asyncio.run(main())
    if errs == 0 and failed == 0:
        print("\nSMOKE OK: admin shell loads with no JS errors or failed requests")
    else:
        print(f"\nSMOKE FAIL: {errs} page errors, {failed} failed requests")