#!/usr/bin/env python3
"""Phase 3 side-by-side screenshots: live source vs frozen dist vs new dist.

Captures 3 pages (home, blog, book-the-colouring-book) from each source,
saves to /workspace/projects/oscar-web/metrics/.

Reads no FvRE code. Just Playwright + local Python http.server.
"""
import asyncio
import os
import subprocess
import time
from pathlib import Path
from playwright.async_api import async_playwright

REPO = Path("/workspace/projects/oscar-web")
METRICS = REPO / "metrics"
METRICS.mkdir(parents=True, exist_ok=True)

# (slug, source path on live site, dist file name in oscarweb/dist/, slug in our dist-generated/)
PAGES = [
    ("home",                        "/",                              "index.html",                "home"),
    ("blog",                        "/blog/",                         "pages/blog/index.html",     "blog"),
    ("book-colouring",              "/book/the-colouring-book/",      "pages/book-the-colouring-book/index.html", "book-the-colouring-book"),
]

VIEWPORT = {"width": 1440, "height": 900}
LIVE_BASE = "https://oscarstreeacademy.org.uk"
FROZEN_DIR = Path("/workspace/projects/oscarweb/dist")
NEW_DIR    = REPO / "dist-v2"

def serve_dir(directory: Path, port: int) -> subprocess.Popen:
    """Start a localhost HTTP server serving directory. Returns the Popen."""
    return subprocess.Popen(
        ["python3", "-m", "http.server", str(port), "--bind", "127.0.0.1", "--directory", str(directory)],
        stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
    )

async def shoot(page, url: str, out: Path):
    await page.goto(url, wait_until="networkidle", timeout=45_000)
    # Give animations + lazy images time to settle
    await page.wait_for_timeout(1500)
    await page.screenshot(path=str(out), full_page=True)
    h = await page.evaluate("document.documentElement.scrollHeight")
    return out.stat().st_size, h

async def main():
    print(f"Metrics dir: {METRICS}")
    print(f"Serving:    frozen={FROZEN_DIR}  new={NEW_DIR}")

    # Start two local servers (need separate ports)
    port_frozen = 18801
    port_new = 18802
    p_frozen = serve_dir(FROZEN_DIR, port_frozen)
    p_new = serve_dir(NEW_DIR, port_new)
    time.sleep(1.5)  # wait for servers

    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=VIEWPORT, device_scale_factor=1)
            page = await ctx.new_page()
            results = []
            for slug, live_path, frozen_rel, new_slug in PAGES:
                live_url = f"{LIVE_BASE}{live_path}"
                frozen_url = f"http://127.0.0.1:{port_frozen}/{frozen_rel}"
                new_url = f"http://127.0.0.1:{port_new}/{new_slug}.html"

                # 1. Live source
                out = METRICS / f"{slug}-1-live.png"
                size, h = await shoot(page, live_url, out)
                results.append((slug, "live", size, h, out.name))

                # 2. Frozen R19 dist (Playwright snapshot from R19 dist source)
                out = METRICS / f"{slug}-2-frozen.png"
                size, h = await shoot(page, frozen_url, out)
                results.append((slug, "frozen", size, h, out.name))

                # 3. Our new dist-v2 (FvRE pipeline output with text_pool fix)
                out = METRICS / f"{slug}-3-new.png"
                size, h = await shoot(page, new_url, out)
                results.append((slug, "new", size, h, out.name))

            await browser.close()
        print("\nScreenshot results:")
        for slug, src, size, h, name in results:
            print(f"  {slug:20s} {src:6s} {size:>10,d}B  h={h:>7d}px  {name}")
    finally:
        p_frozen.terminate()
        p_new.terminate()
        try: p_frozen.wait(timeout=3)
        except: p_frozen.kill()
        try: p_new.wait(timeout=3)
        except: p_new.kill()

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