#!/usr/bin/env python3
"""Verify every CARBON workflow publishes one linked, branded HTML command result."""

from __future__ import annotations

import json
import subprocess
import tempfile
from pathlib import Path


PLUGIN = Path(__file__).resolve().parents[1]
LAUNCHER = PLUGIN / "bin" / "carbon-runtime"
SKILLS = PLUGIN / "skills"
SERVER = PLUGIN / "server" / "index.js"
REQUIRED_REFERENCE = "../../runtime/carbon/references/command-result-reporting.md"
MARK_PATH = "M56 34h112l48 48-48 48V96"


def main() -> int:
    skills = sorted(SKILLS.glob("*/SKILL.md"))
    assert len(skills) == 44
    for skill in skills:
        source = skill.read_text(encoding="utf-8")
        assert source.count(REQUIRED_REFERENCE) == 1, f"{skill} must require exactly one command report"
        assert "Open the CARBON report" in source, f"{skill} does not require a chat link"

    server = SERVER.read_text(encoding="utf-8")
    assert 'name: "carbon_publish_command_report"' in server
    assert "Required CARBON result artifact" in server
    assert "command-result-reporting.md" in server
    assert "recommendedCommands" in server
    assert "Repeat the text confidence meter, biggest gaps, and recommendations in the closing chat" in server
    assert "confidenceMeter" in server
    assert "never a probability" in server
    assert "codexBrowserUrl" in server
    assert "hostPresentation" in server
    assert 'ui://carbon/command-report/v1.html' in server
    assert 'text/html;profile=mcp-app' in server
    assert '"openai/outputTemplate": CARBON_REPORT_APP_URI' in server
    assert 'message.method === "resources/list"' in server
    assert 'message.method === "resources/read"' in server

    with tempfile.TemporaryDirectory(prefix="carbon-command-report-contract-") as temporary:
        root = Path(temporary)
        evidence = root / ".carbon" / "runs" / "browser-contract" / "evidence"
        evidence.mkdir(parents=True)
        start_image = evidence / "01-start.png"
        finding_image = evidence / "02-finding.jpg"
        complete_image = evidence / "03-complete.webp"
        duplicate_image = evidence / "04-duplicate.png"
        sensitive_image = evidence / "05-sensitive.png"
        outside_image = root / "outside.png"
        start_image.write_bytes(b"\x89PNG\r\n\x1a\nstart-state")
        finding_image.write_bytes(b"\xff\xd8\xfffinding-state")
        complete_image.write_bytes(b"RIFF\x08\x00\x00\x00WEBPcomplete-state")
        duplicate_image.write_bytes(start_image.read_bytes())
        sensitive_image.write_bytes(b"\x89PNG\r\n\x1a\nsensitive-state")
        outside_image.write_bytes(b"\x89PNG\r\n\x1a\noutside-state")
        payload = {
            "command": "carbon-help",
            "title": "Login <script>alert(1)</script> direction",
            "summary": "Inspection completed with token sk-1234567890abcdefghij kept private.",
            "status": "partial",
            "scope": "changed login flow",
            "metrics": [
                {"label": "Recommendations", "value": "3", "detail": "ranked by risk", "tone": "good", "icon": "tests"},
                {"label": "Remaining risk", "value": "Medium", "detail": "runtime not observed", "tone": "risk", "icon": "risk"},
            ],
            "sections": [
                {
                    "title": "Recommended path",
                    "icon": "position",
                    "items": [{"title": "Run CARBON Quick", "detail": "Exercise login and session recovery.", "status": "planned", "evidence": "E1 source inspection"}],
                },
                {"title": "Unknowns", "icon": "unknown", "tone": "risk", "bullets": ["Authenticated runtime behavior", "Lockout recovery"]},
            ],
            "findings": [{"severity": "medium", "title": "Runtime evidence missing", "detail": "No browser pass ran.", "evidence": "E0", "fix": "Run the focused flow."}],
            "artifacts": [{"label": "Project", "path": ".", "detail": "Inspected root", "icon": "artifact"}],
            "chatScreenshots": [
                {"path": str(start_image), "label": "Login start state", "caption": "The untouched sign-in form before interaction.", "reason": "Establishes the starting state.", "safeToShow": True},
                {"path": str(finding_image), "label": "Validation failure", "caption": "The highest-risk observed browser failure.", "reason": "Shows the primary finding.", "safeToShow": True},
                {"path": str(complete_image), "label": "Recovery complete", "caption": "The recovered completion state.", "reason": "Closes the visual story.", "safeToShow": True},
                {"path": str(duplicate_image), "label": "Duplicate start", "safeToShow": True},
                {"path": str(sensitive_image), "label": "Sensitive account", "safeToShow": True, "sensitive": True},
                {"path": str(outside_image), "label": "Outside project evidence", "safeToShow": True},
            ],
            "nextActions": ["Run /carbon against the changed login flow"],
            "confidenceMeter": {
                "score": 64,
                "label": "Guarded",
                "basis": "Source inspection and focused checks passed, but authenticated runtime behavior was not observed.",
                "missingItems": [
                    {
                        "item": "Observe authenticated session recovery",
                        "why": "This is the highest-impact behavior still supported only by source inspection.",
                        "nextCommand": "/carbon-browser test the changed login recovery flow",
                    },
                    {
                        "item": "Verify account lockout recovery",
                        "why": "A lockout regression could block legitimate users after failed attempts.",
                        "nextCommand": "carbon-review challenge lockout coverage",
                    },
                ],
            },
            "recommendedCommands": [
                {"command": "carbon-browser", "prompt": "test the changed login recovery flow", "reason": "Adds the missing runtime evidence for the riskiest path."},
                {"command": "carbon-stats", "prompt": "show measured activity", "reason": "Valid built-in commands must survive recommendation filtering."},
                {"command": "carbon-help", "prompt": "repeat this command", "reason": "A command must not recommend itself."},
                {"command": "not-a-carbon-command", "reason": "Unknown commands must be rejected."},
            ],
            "evidenceBoundary": "Project inspection was observed; runtime behavior remains unknown.",
        }
        result = subprocess.run(
            [str(LAUNCHER), "command-report", "render", "--root", str(root), "--payload-json", json.dumps(payload)],
            check=True,
            capture_output=True,
            text=True,
        )
        rendered = json.loads(result.stdout)
        report = Path(rendered["reportPath"])
        assert report.is_absolute() and report.is_file()
        assert report.parent == root.resolve() / ".carbon" / "reports" / "commands"
        assert rendered["singleFile"] is True
        assert rendered["schemaOrigin"]["origin"] == "OpenTest.ai"
        assert rendered["schemaOrigin"]["url"] == "https://www.opentest.ai/"
        assert rendered["schemaOrigin"]["testcase"]["format"] == "otai/testcase"
        assert rendered["schemaOrigin"]["bug"]["format"] == "otai/bug"
        relative_report = report.relative_to(root.resolve()).as_posix()
        assert rendered["chatLink"] == f"[Open the CARBON report]({relative_report})"
        assert rendered["claudeChatLink"] == rendered["absoluteChatLink"]
        assert rendered["claudeFileLink"] == rendered["absoluteChatLink"]
        assert rendered["absoluteChatLink"] == f"[Open the CARBON report]({report})"
        assert rendered["codexChatLink"] == rendered["absoluteChatLink"]
        assert rendered["codexFileLink"] == rendered["absoluteChatLink"]
        assert rendered["presentation"] == {
            "schema": "carbon.in-agent-presentation/v1",
            "preferredSurface": "host-html-preview",
            "fallbackSurface": "host-embedded-browser",
            "externalBrowserFallback": "explicit-only",
            "openByDefault": True,
            "url": report.as_uri(),
            "artifactPath": str(report),
            "chatLink": rendered["chatLink"],
            "claudeChatLink": rendered["claudeChatLink"],
            "codexChatLink": rendered["codexChatLink"],
            "title": "CARBON Report",
            "instruction": "Open this self-contained HTML beside chat. In Codex, open codexChatLink as a native file preview or navigate the built-in Browser to the protected codexBrowserUrl when returned by MCP. In Claude, attach the HTML artifact and use the absolute in-workspace claudeChatLink so its file viewer does not resolve the path against the wrong root. Never launch the operating-system browser. If no internal surface exists, leave chatLink available as the fallback.",
        }
        assert [item["label"] for item in rendered["chatScreenshots"]] == [
            "Login start state", "Validation failure", "Recovery complete",
        ]
        assert all(item["path"].startswith(str((root / ".carbon").resolve())) for item in rendered["chatScreenshots"])
        assert rendered["chatScreenshots"][0]["markdown"] == f"![Login start state]({start_image.resolve()})"
        assert rendered["chatScreenshots"][1]["caption"] == "The highest-risk observed browser failure."
        assert len(rendered["recommendedCommands"]) == 2
        assert rendered["recommendedCommands"][0] == {
            "command": "carbon-browser",
            "prompt": "test the changed login recovery flow",
            "invocation": "/carbon-browser test the changed login recovery flow",
            "reason": "Adds the missing runtime evidence for the riskiest path.",
        }
        assert rendered["recommendedCommands"][1]["command"] == "carbon-stats"
        assert all(item["command"] != "carbon-help" for item in rendered["recommendedCommands"])
        assert rendered["confidenceMeter"]["measured"] is True
        assert rendered["confidenceMeter"]["score"] == 64
        assert rendered["confidenceMeter"]["label"] == "Guarded"
        assert "64/100" in rendered["confidenceMeter"]["textBar"]
        assert len(rendered["confidenceMeter"]["missingItems"]) == 2
        assert list(report.parent.iterdir()) == [report], "command result must be a single standalone file"

        source = report.read_text(encoding="utf-8")
        assert source.lower().count("<!doctype html>") == 1
        assert 'class="decision-hero' in source and 'class="evidence-spine"' in source
        assert "Intent" in source and "Next evidence" in source
        assert MARK_PATH in source and "ENGINEERING CONFIDENCE" in source
        assert "#000000" in source and "#ffffff" in source and "#ff9f43" in source
        assert source.count('class="section-icon') >= 8
        assert "@media(max-width:760px)" in source and "prefers-reduced-motion" in source
        assert "<script>alert(1)</script>" not in source and "&lt;script&gt;alert(1)&lt;/script&gt;" in source
        assert "sk-1234567890abcdefghij" not in source and "[REDACTED]" in source
        assert "<script src=" not in source and "stylesheet" not in source
        assert "file://" in source
        assert "Evidence boundary" in source and "Remaining risk" in source
        assert "Test-case and bug schema origin" in source and "OpenTest.ai" in source
        assert "otai/testcase v1" in source and "otai/bug v1" in source
        assert "Next Carbon commands" in source
        assert "/carbon-browser test the changed login recovery flow" in source
        assert "Adds the missing runtime evidence for the riskiest path." in source
        assert source.count("<button type=\"button\" class=\"command-action\" data-carbon-command-action") == 2
        assert 'data-invocation="/carbon-browser test the changed login recovery flow"' in source
        assert "Run in agent" in source and "Copy command" in source
        assert 'request("ui/message"' in source
        assert 'request("ui/initialize"' in source
        assert "sendFollowUpMessage" in source
        assert "Runs only after you click" in source
        assert "Normal CARBON approval gates still apply" in source
        assert "not-a-carbon-command" not in source
        assert source.index("Evidence boundary") < source.index("Next Carbon commands")
        assert "Shipping confidence" in source
        assert "64<small>/100</small>" in source
        assert "Evidence strength and breadth" in source
        assert "not probability" in source
        assert "Biggest gaps to stronger confidence" in source
        assert "Observe authenticated session recovery" in source
        assert "/carbon-browser test the changed login recovery flow" in source

        fallback_result = subprocess.run(
            [
                str(LAUNCHER), "command-report", "render", "--root", str(root),
                "--payload-json", json.dumps({
                    "command": "carbon-release",
                    "title": "Release decision recorded",
                    "summary": "The decision is ready for independent challenge.",
                    "status": "completed",
                    "scope": "checkout release",
                }),
            ],
            check=True,
            capture_output=True,
            text=True,
        )
        fallback = json.loads(fallback_result.stdout)
        assert len(fallback["recommendedCommands"]) >= 2
        assert all(item["command"] != "carbon-release" for item in fallback["recommendedCommands"])
        assert all(item["prompt"] and item["reason"] for item in fallback["recommendedCommands"])
        assert fallback["confidenceMeter"]["measured"] is False
        assert fallback["confidenceMeter"]["score"] is None
        assert fallback["confidenceMeter"]["label"] == "Not assessed"
        assert "NOT ASSESSED" in fallback["confidenceMeter"]["textBar"]
        assert len(fallback["confidenceMeter"]["missingItems"]) >= 2
        fallback_html = Path(fallback["reportPath"]).read_text(encoding="utf-8")
        assert "NOT<br>ASSESSED" in fallback_html
        assert "No evidence-backed confidence index was supplied" in fallback_html

        inspected = subprocess.run(
            [str(LAUNCHER), "workspace", "inspect", "--root", str(root)],
            check=True,
            capture_output=True,
            text=True,
        )
        workspace = json.loads(inspected.stdout)
        assert workspace["firstRun"] is True and workspace["onboardingComplete"] is False

    print("PASS: all 44 CARBON workflows require a linked, branded, secret-redacted HTML result with an evidence-safe shipping-confidence meter, biggest gaps, and contextual next commands.")
    return 0


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