#!/usr/bin/env python3
"""Headless Chrome screenshots of the Go Around 3D terrain demo (SwiftShader WebGL)."""

from __future__ import annotations

import asyncio
import base64
import json
import os
import subprocess
import sys
import time
import urllib.request
from pathlib import Path

import websockets

ROOT = Path(__file__).resolve().parent
SHOTS = ROOT / "shots"
SHOTS.mkdir(exist_ok=True)

CHROME = os.environ.get("CHROME", "google-chrome")
PORT = int(os.environ.get("CDP_PORT", "9236"))
BASE = os.environ.get("DEMO_URL", "http://127.0.0.1:8765")

# Default live-weather preview (fx defaults to weather,wind)
LIVE_VIEWS = ("table_mountain", "peninsula")
LIVE_SIZES = (
    ("390x844", 390, 844),
    ("1440x900", 1440, 900),
)

# Dedicated idea previews. Phone shots for the main ones.
IDEAS = (
    # name, fx, view, extra query, phone too, hour
    ("weather", "weather", "table_mountain", "", True, None),
    ("wind", "wind", "table_mountain", "", True, None),
    ("clouds", "clouds", "table_mountain", "", True, None),
    ("sky", "sky", "table_mountain", "", True, None),
    ("scrubber", "scrubber,weather", "table_mountain", "&hour=14", True, 14),
    ("runway", "runway", "fact", "", True, None),
    ("badge", "badge,weather", "table_mountain", "", True, None),
    ("orbit", "orbit", "table_mountain", "", False, None),
    ("sea", "sea", "table_bay", "", False, None),
    ("trees", "trees", "hout_bay", "", False, None),
    ("all", "all", "table_mountain", "", True, None),
)


class CDP:
    def __init__(self, ws):
        self.ws = ws
        self.n = 0
        self.pending = {}
        self.session_id = None

    async def call(self, method, **params):
        self.n += 1
        mid = self.n
        fut = asyncio.get_event_loop().create_future()
        self.pending[mid] = fut
        msg = {"id": mid, "method": method, "params": params}
        if self.session_id and not method.startswith("Target."):
            msg["sessionId"] = self.session_id
        await self.ws.send(json.dumps(msg))
        return await asyncio.wait_for(fut, timeout=90)

    async def reader(self):
        async for raw in self.ws:
            msg = json.loads(raw)
            mid = msg.get("id")
            if mid in self.pending:
                if "error" in msg:
                    self.pending[mid].set_exception(RuntimeError(msg["error"]))
                else:
                    self.pending[mid].set_result(msg.get("result", {}))
                del self.pending[mid]


async def evaluate(cdp, expression):
    res = await cdp.call("Runtime.evaluate", expression=expression, returnByValue=True, awaitPromise=False)
    return (res.get("result") or {}).get("value")


async def wait_ready(cdp, timeout=50, need_weather=True):
    t0 = time.time()
    last = None
    while time.time() - t0 < timeout:
        val = await evaluate(
            cdp,
            "({ready: window.__READY === true, weather: window.__WEATHER_READY === true,"
            " err: window.__ERROR || null, href: location.href,"
            " wx: window.__WEATHER || null, fx: window.__FX || null})",
        )
        last = val
        if val and val.get("err"):
            raise RuntimeError(f"page error: {val['err']}")
        if val and val.get("ready") and (val.get("weather") or not need_weather):
            return val
        # If terrain is ready but weather is slow, wait until timeout-2 then accept
        if val and val.get("ready") and time.time() - t0 > timeout - 3:
            return val
        await asyncio.sleep(0.25)
    raise TimeoutError(f"terrain not ready after {timeout}s; last={last}")


async def capture(cdp, path: Path):
    png = await cdp.call(
        "Page.captureScreenshot",
        format="png",
        fromSurface=True,
        captureBeyondViewport=False,
    )
    data = base64.b64decode(png["data"])
    path.write_bytes(data)
    try:
        from PIL import Image
        size = Image.open(path).size
    except Exception:
        size = None
    return data, size


async def set_view(cdp, name, hour=None):
    await evaluate(cdp, f"window.setView({name!r})")
    if hour is not None:
        await evaluate(cdp, f"window.__setHour && window.__setHour({int(hour)})")
    await asyncio.sleep(0.5)
    return await evaluate(cdp, "(window.__captureStats && window.__captureStats()) || window.__STATS")


def start_chrome(user_data):
    args = [
        CHROME,
        "--headless=new",
        f"--remote-debugging-port={PORT}",
        f"--user-data-dir={user_data}",
        "--no-first-run",
        "--no-default-browser-check",
        "--no-sandbox",
        "--disable-dev-shm-usage",
        "--disable-gpu-sandbox",
        "--ignore-gpu-blocklist",
        "--use-gl=angle",
        "--use-angle=swiftshader-webgl",
        "--enable-unsafe-swiftshader",
        "--enable-webgl",
        "--enable-webgl2",
        "--hide-scrollbars",
        "--window-size=1440,900",
        "--about-blank",
    ]
    proc = subprocess.Popen(args, stdout=subprocess.DEVNULL, stderr=subprocess.PIPE)
    url = f"http://127.0.0.1:{PORT}/json/version"
    for _ in range(50):
        try:
            with urllib.request.urlopen(url, timeout=1) as r:
                return proc, json.loads(r.read().decode())
        except Exception:
            if proc.poll() is not None:
                err = proc.stderr.read().decode(errors="replace") if proc.stderr else ""
                raise RuntimeError(f"chrome exited {proc.returncode}: {err}")
            time.sleep(0.15)
    raise RuntimeError("chrome DevTools did not start")


def ok_3d(stats):
    mesh = (stats or {}).get("mesh") or {}
    lum = (stats or {}).get("luminance") or {}
    return (
        mesh.get("maxY", 0) > 800
        and lum.get("std", 0) > 4
        and lum.get("max", 0) > lum.get("min", 0) + 10
        and (stats or {}).get("nonBackgroundRatio", 0) > 0.02
    )


async def shot_page(cdp, width, height, mobile, url, view, hour=None):
    await cdp.call(
        "Emulation.setDeviceMetricsOverride",
        width=width,
        height=height,
        deviceScaleFactor=1,
        mobile=mobile,
    )
    await cdp.call("Page.navigate", url=url)
    ready = await wait_ready(cdp, timeout=50, need_weather=True)
    stats = await set_view(cdp, view, hour=hour)
    return ready, stats


async def run():
    user_data = "/tmp/chrome-terrain3d-live"
    os.makedirs(user_data, exist_ok=True)
    proc, version = start_chrome(user_data)
    print("Chrome:", version.get("Browser"), "ws:", version.get("webSocketDebuggerUrl"))
    report = {"browser": version.get("Browser"), "weather": None, "files": [], "ideas": {}}
    try:
        async with websockets.connect(version["webSocketDebuggerUrl"], max_size=40 * 1024 * 1024) as ws:
            cdp = CDP(ws)
            reader = asyncio.create_task(cdp.reader())
            created = await cdp.call("Target.createTarget", url="about:blank")
            attached = await cdp.call("Target.attachToTarget", targetId=created["targetId"], flatten=True)
            cdp.session_id = attached["sessionId"]
            await cdp.call("Page.enable")
            await cdp.call("Runtime.enable")
            await cdp.call(
                "Emulation.setDefaultBackgroundColorOverride",
                color={"r": 7, "g": 11, "b": 20, "a": 255},
            )

            # --- default live weather preview ---
            for label, width, height in LIVE_SIZES:
                for view in LIVE_VIEWS:
                    url = f"{BASE}/index.html?view={view}&shot=1"
                    print(f"\n=== live {label} {view} ===")
                    ready, stats = await shot_page(cdp, width, height, label.startswith("390"), url, view)
                    if ready.get("wx") and not report["weather"]:
                        report["weather"] = ready["wx"]
                        print("  weather:", json.dumps(ready["wx"], indent=2)[:1200])
                    path = SHOTS / f"live-{view.replace('_', '-')}-{label}.png"
                    data, size = await capture(cdp, path)
                    entry = {
                        "file": str(path),
                        "bytes": len(data),
                        "pixels": size,
                        "ok_3d": ok_3d(stats),
                        "kind": "live",
                        "view": view,
                        "stats": {
                            "luminance": (stats or {}).get("luminance"),
                            "goldRatio": (stats or {}).get("goldRatio"),
                            "nonBackgroundRatio": (stats or {}).get("nonBackgroundRatio"),
                        },
                    }
                    report["files"].append(entry)
                    print(f"  wrote {path} {len(data)} bytes size={size} ok_3d={entry['ok_3d']} gold={entry['stats'].get('goldRatio')}")

            # --- per-idea shots ---
            for name, fx, view, extra, phone, hour in IDEAS:
                jobs = [("1440", 1440, 900, False)]
                if phone:
                    jobs.append(("390", 390, 844, True))
                for tag, width, height, mobile in jobs:
                    url = f"{BASE}/index.html?view={view}&shot=1&fx={fx}{extra}"
                    print(f"\n=== idea {name} {tag} {view} fx={fx} ===")
                    ready, stats = await shot_page(cdp, width, height, mobile, url, view, hour=hour)
                    if ready.get("wx") and not report["weather"]:
                        report["weather"] = ready["wx"]
                    fname = f"live-idea-{name}-{tag}.png"
                    path = SHOTS / fname
                    data, size = await capture(cdp, path)
                    entry = {
                        "file": str(path),
                        "bytes": len(data),
                        "pixels": size,
                        "ok_3d": ok_3d(stats),
                        "kind": "idea",
                        "idea": name,
                        "fx": fx,
                        "view": view,
                        "stats": {
                            "luminance": (stats or {}).get("luminance"),
                            "goldRatio": (stats or {}).get("goldRatio"),
                            "nonBackgroundRatio": (stats or {}).get("nonBackgroundRatio"),
                        },
                        "weather": ready.get("wx"),
                    }
                    report["files"].append(entry)
                    report["ideas"].setdefault(name, []).append(str(path))
                    print(f"  wrote {path} {len(data)} bytes size={size} ok_3d={entry['ok_3d']} gold={entry['stats'].get('goldRatio')}")

            reader.cancel()
    finally:
        proc.terminate()
        try:
            proc.wait(timeout=5)
        except subprocess.TimeoutExpired:
            proc.kill()

    out = SHOTS / "live_capture_report.json"
    out.write_text(json.dumps(report, indent=2))
    print("\nReport:", out)
    failed = [f for f in report["files"] if not f["ok_3d"]]
    if failed:
        print(f"FAILED 3D checks on {len(failed)} shots")
        for f in failed:
            print("  -", f["file"], f.get("stats"))
        sys.exit(2)
    print("All shots passed 3D checks.")


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