#!/usr/bin/env python3
"""Verify every CARBON workflow explains its high-level approach before acting."""

from pathlib import Path


ROOT = Path(__file__).resolve().parents[1]
SKILLS = ROOT / "skills"
REFERENCE = ROOT / "runtime" / "carbon" / "references" / "command-start-preview.md"
SERVER = ROOT / "server" / "index.js"
README = ROOT / "README.md"
COMMANDS = ROOT / "COMMANDS.md"
REQUIRED_REFERENCE = "../../runtime/carbon/references/command-start-preview.md"


def main() -> int:
    skills = sorted(SKILLS.glob("*/SKILL.md"))
    assert len(skills) == 44, f"expected 44 skills, found {len(skills)}"
    for skill in skills:
        source = skill.read_text(encoding="utf-8")
        assert source.count(REQUIRED_REFERENCE) == 1, (
            f"{skill} must require exactly one command start preview"
        )
        reference_at = source.index(REQUIRED_REFERENCE)
        first_tool_guidance = min(
            [
                position
                for phrase in ("call `", "run `", "carbon_set_preferences")
                if (position := source.find(phrase)) >= 0
            ]
            or [len(source)]
        )
        assert reference_at < first_tool_guidance, (
            f"{skill} does not require the preview before tool guidance"
        )

    preview = REFERENCE.read_text(encoding="utf-8")
    for phrase in (
        "Every user-invoked CARBON workflow begins by explaining its approach in chat",
        "Show this preview before project inspection",
        "planning, execution, or",
        "**CARBON will:**",
        "Analyze the codebase, current change, available product artifacts, and intended behavior.",
        "Identify the highest product and release risks",
        "Inventory existing tests and evidence",
        "Verify business value: the promised customer outcome",
        "Generate at least five candidates for every top-level quality domain",
        "choose at most 20 that add the most confidence",
        "preserve the unrun cut line for `/carbon-more`",
        "run safe local tests when execution is requested",
        "explain shipping confidence, remaining risk",
        "preview itself\n  authorizes gated action",
        "Immediately after sending the preview",
        "carbon_command_progress` with `action=start",
        "open it in the\n  Artifacts pane beside chat",
        "call\n`carbon_command_progress action=update`",
        "refreshes every second",
        "automatically finalizes the newest matching",
    ):
        assert phrase in preview, f"start-preview reference is missing {phrase!r}"

    server = SERVER.read_text(encoding="utf-8")
    for phrase in (
        "function startupPreviewFor(prompt)",
        "function startupPreviewAppendix(prompt)",
        "CARBON command start requirement",
        "Before any inspection, tool call, planning, execution, or mutation",
        "text: `${startPreview}",
        "call carbon_command_progress action=start before any other tool",
        "the exact active project root",
        "openByDefault is a host request, not proof",
        "navigate the built-in Browser to codexBrowserUrl",
        "call carbon_command_progress action=update after every major step",
        "case \"carbon\"",
        "const domain = TESTING_DOMAINS.find",
    ):
        assert phrase in server, f"MCP start-preview contract is missing {phrase!r}"

    for document in (README, COMMANDS):
        text = document.read_text(encoding="utf-8")
        assert "CARBON will:" in text, f"{document.name} does not document command previews"
        assert "before" in text.lower() and "tool" in text.lower(), (
            f"{document.name} does not explain when the preview appears"
        )

    print(
        "PASS: 44 workflows require a tailored high-level CARBON will preview "
        "before inspection or tool use; the main workflow covers analysis, risk, "
        "business value, broad candidate generation, bounded execution, deferred coverage, reporting, and shipping confidence."
    )
    return 0


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