#!/usr/bin/env python3
"""Capture proposal/pages HTML mockups → powerpoint/screenshots/*.png

Requires Chromium and a local HTTP server (started automatically).
"""

from __future__ import annotations

import subprocess
import sys
import time
import urllib.request
from pathlib import Path

ROOT = Path(__file__).resolve().parent
PAGES = ROOT.parent / "pages"
SHOTS = ROOT / "screenshots"
PORT = 8765

PAGES_LIST = [
    "index.html",
    "public-home.html",
    "public-about.html",
    "public-contact.html",
    "public-unsubscribe.html",
    "public-404.html",
    "public-under-construction.html",
    "portal-login.html",
    "portal-dashboard.html",
    "portal-leads.html",
    "portal-lead-detail.html",
    "portal-analytics.html",
    "portal-contacts.html",
    "portal-contacts-import.html",
    "portal-campaign.html",
    "portal-campaign-report.html",
    "portal-postcard-designer.html",
    "portal-social.html",
    "portal-social-accounts.html",
]


def find_chromium() -> str:
    for candidate in ("chromium", "google-chrome", "google-chrome-stable", "/snap/bin/chromium"):
        path = Path(candidate) if candidate.startswith("/") else None
        if path and path.exists():
            return str(path)
        found = subprocess.run(["which", candidate], capture_output=True, text=True)
        if found.returncode == 0 and found.stdout.strip():
            return found.stdout.strip()
    raise SystemExit("Chromium/Chrome not found")


def main() -> None:
    SHOTS.mkdir(parents=True, exist_ok=True)
    chromium = find_chromium()
    server = subprocess.Popen(
        [sys.executable, "-m", "http.server", str(PORT)],
        cwd=str(PAGES),
        stdout=subprocess.DEVNULL,
        stderr=subprocess.DEVNULL,
    )
    try:
        for _ in range(30):
            try:
                urllib.request.urlopen(f"http://127.0.0.1:{PORT}/index.html", timeout=1)
                break
            except Exception:
                time.sleep(0.2)
        else:
            raise SystemExit("HTTP server failed to start")

        for page in PAGES_LIST:
            stem = page.removesuffix(".html")
            out = SHOTS / f"{stem}.png"
            url = f"http://127.0.0.1:{PORT}/{page}"
            print(f"screenshot {page} → {out.name}")
            subprocess.run(
                [
                    chromium,
                    "--headless=new",
                    "--disable-gpu",
                    "--no-sandbox",
                    "--hide-scrollbars",
                    "--window-size=1440,900",
                    f"--virtual-time-budget=5000",
                    f"--screenshot={out}",
                    url,
                ],
                check=True,
                capture_output=True,
            )
        print(f"Done: {len(PAGES_LIST)} screenshots in {SHOTS}")
    finally:
        server.terminate()
        server.wait(timeout=5)


if __name__ == "__main__":
    main()
