#!/usr/bin/env python3
"""Verify the real live-view demo and the public multi-scenario replay page."""

from __future__ import annotations

import json
import os
import re
import signal
import subprocess
import tempfile
from pathlib import Path


ROOT = Path(__file__).resolve().parents[1]
DEMO = ROOT / "scripts" / "run-command-progress-demo.py"
SITE = Path("/Users/jasonarbon/Desktop/cowork/plugins")


def main() -> int:
    with tempfile.TemporaryDirectory(prefix="carbon-live-demo-") as directory:
        project = Path(directory) / "project"
        completed = subprocess.run(
            ["python3", str(DEMO), "--root", str(project), "--interval", "0.02", "--viewer-ttl", "60"],
            cwd=ROOT,
            text=True,
            capture_output=True,
            check=True,
        )
        assert "CARBON_DEMO_URL=http://127.0.0.1:" in completed.stdout
        states = sorted((project / ".carbon" / "reports" / "live" / "commands").glob("*.json"))
        assert len(states) == 1
        state = json.loads(states[0].read_text(encoding="utf-8"))
        assert state["status"] == "partial"
        assert state["confidence"]["start"] == 42
        assert state["confidence"]["current"] == 68
        assert state["confidence"]["delta"] == 26
        assert state["risks"][0]["status"] == "mitigated"
        assert state["risks"][1]["status"] == "unknown"
        assert len(state["evidence"]) == 2
        assert state["currentAction"]["title"].startswith("Verify the repair")
        for ready in (project / ".carbon" / "runtime").glob("demo-viewer-*.json"):
            pid = int(json.loads(ready.read_text(encoding="utf-8"))["pid"])
            try:
                os.kill(pid, signal.SIGTERM)
            except ProcessLookupError:
                pass

    page = (SITE / "carbon-demo.html").read_text(encoding="utf-8")
    for phrase in (
        "Checkout recovery",
        "AI-generated login",
        "API schema change",
        "Accessibility regression",
        'data-speed="15000"',
        'data-speed="90000"',
        'data-speed="300000"',
        "Demonstration, not a measured product result.",
        "Why this test?",
        'id="demo-announcer"',
        'role="progressbar"',
        'byId("demo-confidence-start").textContent=stages[0].confidence',
    ):
        assert phrase in page
    assert len(re.findall(r"data-scenario=", page)) == 4
    home = (SITE / "index.html").read_text(encoding="utf-8")
    assert "carbon-mini-demo" in home
    assert 'href="carbon-demo.html"' in home
    build = (ROOT / "scripts" / "build-deploy-folder.sh").read_text(encoding="utf-8")
    assert "carbon-demo.html" in build
    print("PASS: real live-view checkout story plus 15-second, 90-second, five-minute, and four-scenario public demos are deterministic, evidence-honest, and deployment-packaged.")
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
