#!/usr/bin/env python3
"""Verify universal live CARBON command progress and honest durable updates."""

from __future__ import annotations

import json
import subprocess
import tempfile
from pathlib import Path


ROOT = Path(__file__).resolve().parents[1]
SCRIPT = ROOT / "runtime" / "carbon" / "scripts" / "carbon_command_progress.py"
UI = ROOT / "ui" / "command-progress.html"
SERVER = ROOT / "server" / "index.js"
REFERENCE = ROOT / "runtime" / "carbon" / "references" / "command-start-preview.md"
ALIAS = ROOT / "scripts" / "install-claude-aliases.py"


def run(*args: str) -> dict:
    completed = subprocess.run(
        ["python3", str(SCRIPT), *args],
        text=True,
        capture_output=True,
        check=True,
    )
    return json.loads(completed.stdout)


def main() -> int:
    with tempfile.TemporaryDirectory(prefix="carbon-command-progress-") as directory:
        project = Path(directory) / "empty-project"
        project.mkdir()
        evidence_image = project / ".carbon" / "demo" / "checkout.png"
        evidence_image.parent.mkdir(parents=True)
        evidence_image.write_bytes(bytes.fromhex("89504e470d0a1a0a"))
        symlink_image = project / ".carbon" / "demo" / "checkout-link.png"
        symlink_image.symlink_to(evidence_image)
        rejected_symlink = subprocess.run(
            [
                "python3", str(SCRIPT), "start", "--root", str(project),
                "--payload-json", json.dumps({
                    "command": "carbon-ui",
                    "steps": [{"id": "inspect", "title": "Inspect"}],
                    "evidence": [{
                        "id": "linked",
                        "label": "Linked evidence",
                        "imagePath": str(symlink_image),
                        "safeToShow": True,
                    }],
                }),
            ],
            text=True,
            capture_output=True,
            check=False,
        )
        assert rejected_symlink.returncode != 0, "symlink evidence should be rejected"
        started = run(
            "start",
            "--root", str(project),
            "--payload-json", json.dumps({
                "command": "carbon-help",
                "title": "Understand this project",
                "scope": "Empty project",
                "reason": "The project has no files, so CARBON must preserve that evidence boundary.",
                "steps": [
                    {"id": "inspect", "title": "Inspect context", "why": "Project contents determine what can be tested.", "risk": "unknown scope"},
                    {"id": "risk", "title": "Prioritize risk"},
                    {"id": "report", "title": "Publish the result"},
                ],
                "confidence": {"start": 12, "current": 18, "label": "Context only", "basis": "The empty workspace was observed."},
                "risks": [{"id": "scope", "label": "No runnable surface", "severity": "high", "status": "unknown"}],
                "evidence": [{"id": "checkout", "label": "Demo evidence", "type": "screenshot", "status": "captured", "safeToShow": True, "imagePath": str(evidence_image)}],
            }),
        )
        state_path = Path(started["statePath"])
        assert state_path.is_file()
        assert started["progress"]["status"] == "running"
        assert started["progress"]["progress"]["total"] == 3
        assert started["progress"]["steps"][0]["status"] == "running"
        assert started["progress"]["currentAction"]["why"].startswith("Project contents")
        assert started["progress"]["confidence"]["delta"] == 6
        assert started["progress"]["risks"][0]["status"] == "unknown"
        assert started["progress"]["evidence"][0]["imageAvailable"] is True

        updated = run(
            "update",
            "--root", str(project),
            "--progress-id", started["progressId"],
            "--payload-json", json.dumps({
                "phase": "Prioritizing risk",
                "summary": "Context inspected without a runnable target.",
                "reason": "No execution target exists, so the recommendation is the useful outcome.",
                "steps": [{"id": "inspect", "status": "completed", "summary": "The project is empty."}],
                "advance": True,
                "metrics": [{"label": "Files", "value": "0", "detail": "Observed locally"}],
                "confidence": {"start": 12, "current": 22, "label": "Scope understood", "basis": "The lack of files is directly observed."},
                "evidenceBoundary": "Project structure was observed; runtime behavior was not executed.",
            }),
        )
        assert updated["progress"]["progress"]["completed"] == 1
        assert updated["progress"]["steps"][1]["status"] == "running"
        assert updated["progress"]["metrics"][0]["value"] == "0"
        assert updated["progress"]["confidence"]["delta"] == 10
        assert updated["progress"]["evidenceBoundary"] == "Project structure was observed; runtime behavior was not executed."

        completed = run(
            "complete-latest",
            "--root", str(project),
            "--command", "carbon_help",
            "--payload-json", json.dumps({
                "status": "completed",
                "phase": "Complete",
                "summary": "Published the project-specific recommendation.",
                "reportPath": str(project / ".carbon" / "reports" / "commands" / "report.html"),
            }),
        )
        assert completed["matched"] is True
        assert completed["progressId"] == started["progressId"]
        assert completed["progress"]["status"] == "completed"
        assert completed["progress"]["summary"].startswith("Published")
        assert completed["progress"]["reportPath"] == ".carbon/reports/commands/report.html"
        assert completed["progress"]["progress"]["completed"] == 3
        assert all(step["status"] == "completed" for step in completed["progress"]["steps"])

        second = run(
            "complete-latest",
            "--root", str(project),
            "--command", "carbon-help",
            "--payload-json", json.dumps({"status": "completed"}),
        )
        assert second["matched"] is False, "terminal progress must not be finalized twice"

        alias_started = run(
            "start",
            "--root", str(project),
            "--payload-json", json.dumps({
                "command": "carbon-chatbot",
                "title": "Generate chatbot tests",
                "steps": [{"id": "generate", "title": "Generate the suite"}],
            }),
        )
        alias_completed = run(
            "complete-latest",
            "--root", str(project),
            "--command", "chatbot",
            "--payload-json", json.dumps({"status": "completed", "summary": "Suite generated."}),
        )
        assert alias_completed["matched"] is True
        assert alias_completed["progressId"] == alias_started["progressId"]

    ui = UI.read_text(encoding="utf-8")
    for phrase in (
        "Live · updates every second",
        "High-level progress",
        "Expected flow",
        "Completed steps",
        "Live testing mission",
        "Why this test?",
        "Confidence movement",
        "Live evidence",
        "Risks and unknowns",
        "/api/command-progress",
        "/api/command-evidence/",
        "X-Carbon-Command-Token",
        "container-type:inline-size",
        "strong.unmeasured",
        'current.classList.toggle("unmeasured",!hasCurrent)',
    ):
        assert phrase in ui
    assert ".risk-list,#completed{" in ui
    assert ".risk-list,.completed{" not in ui
    assert "#completed li{" in ui

    server = SERVER.read_text(encoding="utf-8")
    for phrase in (
        'name: "carbon_command_progress"',
        'case "carbon_command_progress"',
        "launchCommandProgressViewer",
        "writeLiveCommandArtifact",
        "complete-latest",
        "openByDefault: true",
        "privacy-approved evidence previews",
        "confidence: args.confidence",
        "risks: args.risks",
        "evidence: args.evidence",
    ):
        assert phrase in server

    runtime = SCRIPT.read_text(encoding="utf-8")
    assert 'route == "/favicon.ico"' in runtime
    assert 'route.startswith("/api/command-evidence/")' in runtime
    assert "img-src 'self' data: blob:" in runtime

    reference = REFERENCE.read_text(encoding="utf-8")
    assert "required for every command" in reference
    assert "without waiting\nfor the user to click" in reference
    assert "After every major step" in reference
    alias = ALIAS.read_text(encoding="utf-8")
    assert "carbon_command_progress action=start" in alias
    assert "without waiting for the user to click" in alias

    print("PASS: every CARBON workflow requires a durable auto-open live command page with one-second progress, honest step updates, terminal report finalization, and Codex/Claude side-view guidance.")
    return 0


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