#!/usr/bin/env python3
"""Verify every CARBON-generated HTML surface uses the marketing brand shell."""

from __future__ import annotations

import json
import subprocess
import sys
import tempfile
from pathlib import Path


PLUGIN = Path(__file__).resolve().parents[1]
RUNTIME = PLUGIN / "runtime" / "carbon" / "scripts"
RUN = RUNTIME / "carbon_run.py"
LEARN = RUNTIME / "carbon_learn.py"
FRAMEWORK = RUNTIME / "carbon_framework.py"
DASHBOARD = PLUGIN / "bin" / "carbon-confidence-dashboard"
EXECUTION_PLAN = PLUGIN / "ui" / "execution-plan.html"
STATIC_HTML_SURFACES = {
    "live command progress": PLUGIN / "ui" / "command-progress.html",
    "live execution plan": EXECUTION_PLAN,
    "in-agent report loader": PLUGIN / "ui" / "report-loader.html",
    "settings report": PLUGIN / "ui" / "settings.html",
    "test-library report": PLUGIN / "ui" / "tests.html",
}
PYTHON_HTML_VARIANTS = {
    "import-bake renderer": (RUNTIME / "carbon_bake.py", 1),
    "chatbot-suite renderer": (RUNTIME / "carbon_chatbot.py", 1),
    "command/WCAG/ACR renderers": (RUNTIME / "carbon_command_report.py", 3),
    "framework renderer": (RUNTIME / "carbon_framework.py", 1),
    "intelligence renderer": (RUNTIME / "carbon_intelligence.py", 1),
    "Learn renderer": (RUNTIME / "carbon_learn.py", 1),
    "persona-journey renderer": (RUNTIME / "carbon_persona_journeys.py", 1),
    "run renderer": (RUNTIME / "carbon_run.py", 1),
}
JAVASCRIPT_HTML_VARIANTS = {
    "live handoff renderers": (PLUGIN / "server" / "index.js", 2),
    "confidence dashboard renderer": (DASHBOARD, 1),
}
MARK_PATH = "M56 34h112l48 48-48 48V96"
LEGACY_BRAND_TOKENS = ("#f59e0b", "#38c9e8", "Testing AI · Confidence Engineering")
RISK_COLOR = "#ff9f43"


def run(*args: str) -> str:
    result = subprocess.run(args, check=True, capture_output=True, text=True)
    return result.stdout.strip()


def assert_branded(path: Path, label: str) -> None:
    source = path.read_text(encoding="utf-8")
    assert 'rel="icon"' in source, f"{label} is missing the CARBON favicon declaration"
    assert "data:image/svg+xml" in source, f"{label} favicon is not self-contained"
    assert MARK_PATH in source, f"{label} is missing the CARBON cut-C mark"
    assert "ENGINEERING CONFIDENCE" in source, f"{label} is missing the CARBON tagline"
    assert "#000000" in source or "#000" in source, f"{label} is missing a pure-black canvas"
    assert "#ffffff" in source or "#fff" in source, f"{label} is missing white brand ink"
    assert RISK_COLOR in source, f"{label} is missing the CARBON orange risk treatment"
    assert source.count('class="section-icon') >= 3, f"{label} is missing section-level custom SVG icons"
    for token in LEGACY_BRAND_TOKENS:
        assert token not in source, f"{label} retained legacy brand token {token}"


def assert_favicon_contract() -> int:
    canonical = (RUNTIME / "carbon_brand.py").read_text(encoding="utf-8")
    assert "REPORT_FAVICON" in canonical, "canonical CARBON favicon constant is missing"
    assert "data:image/svg+xml" in canonical, "canonical CARBON favicon is not self-contained"
    assert MARK_PATH in canonical, "canonical favicon is not the official CARBON cut-C mark"

    variants = 0
    for label, path in STATIC_HTML_SURFACES.items():
        source = path.read_text(encoding="utf-8")
        assert source.count('rel="icon"') == 1, f"{label} must declare exactly one favicon"
        assert "data:image/svg+xml" in source and MARK_PATH in source, f"{label} does not use the official self-contained cut-C favicon"
        variants += 1

    for label, (path, expected) in PYTHON_HTML_VARIANTS.items():
        source = path.read_text(encoding="utf-8")
        actual = source.count('rel="icon"')
        assert actual == expected, f"{label} covers {actual} of {expected} HTML variants with a favicon"
        assert "REPORT_FAVICON" in source, f"{label} does not use the canonical Python favicon"
        variants += expected

    for label, (path, expected) in JAVASCRIPT_HTML_VARIANTS.items():
        source = path.read_text(encoding="utf-8")
        actual = source.count('rel="icon"')
        assert actual == expected, f"{label} covers {actual} of {expected} HTML variants with a favicon"
        assert "data:image/svg+xml" in source and MARK_PATH in source, f"{label} does not use the official self-contained cut-C favicon"
        variants += expected
    return variants


def main() -> int:
    favicon_variants = assert_favicon_contract()
    sys.path.insert(0, str(RUNTIME))
    from carbon_bake import render_report as render_bake_report
    from carbon_command_report import render as render_command_report

    with tempfile.TemporaryDirectory(prefix="carbon-report-brand-") as temporary:
        root = Path(temporary)

        plan = {
            "title": "CARBON brand contract",
            "target": "https://example.test",
            "environment": "isolated local fixture",
            "scope": ["report brand shell"],
            "tests": [{
                "id": "BRAND-001",
                "title": "Render the CARBON report shell",
                "priority": "P1",
                "type": "visual",
                "steps": ["Open the generated report"],
                "oracle": "The white cut-C mark appears on a pure-black canvas",
                "evidenceRequirements": ["screenshot"],
            }],
        }
        plan_path = root / "plan.json"
        plan_path.write_text(json.dumps(plan), encoding="utf-8")
        run_dir = Path(run(
            sys.executable, str(RUN), "init", "--root", str(root), "--plan", str(plan_path),
            "--mode", "quick", "--target", "https://example.test", "--run-id", "brand-run",
        ))

        learn_dir = Path(run(
            sys.executable, str(LEARN), "init", "--root", str(root),
            "--target", "https://example.test", "--surface", "brand preview", "--kind", "web",
            "--session-id", "brand-learn", "--title", "CARBON Learn brand contract",
        ))

        framework_report = Path(run(sys.executable, str(FRAMEWORK), "report", "--root", str(root)))

        bake_dir = root / ".carbon" / "tests" / "bake-runs" / "BAKE-BRAND"
        bake_dir.mkdir(parents=True, exist_ok=True)
        bake_report = render_bake_report(root, {
            "schema": "carbon.import-bake/v1",
            "id": "BAKE-BRAND",
            "status": "prepared",
            "tests": [],
        })

        dashboard_input = root / "dashboard.json"
        dashboard_output = root / "dashboard.html"
        dashboard_input.write_text(json.dumps({
            "title": "CARBON confidence",
            "decision": "MORE EVIDENCE",
            "confidence": "low",
            "summary": "Brand contract fixture",
            "metrics": [{"label": "Reports", "value": "6", "status": "good"}],
        }), encoding="utf-8")
        run("node", str(DASHBOARD), "--input", str(dashboard_input), "--output", str(dashboard_output))

        command_report = Path(render_command_report(root, {
            "command": "carbon-help",
            "title": "CARBON command report brand contract",
            "summary": "Every command returns a modern linked HTML result.",
            "status": "completed",
            "metrics": [{"label": "Commands", "value": "25", "tone": "good", "icon": "tests"}],
            "sections": [{"title": "Result", "icon": "confidence", "bullets": ["Single-file HTML"]}],
            "nextActions": ["Open the CARBON report"],
        })["reportPath"])

        rendered = {
            "run report": run_dir / "report.html",
            "Learn report": learn_dir / "report.html",
            "framework report": framework_report,
            "import-bake report": bake_report,
            "confidence dashboard": dashboard_output,
            "execution-plan page": EXECUTION_PLAN,
            "universal command report": command_report,
        }
        for label, path in rendered.items():
            assert path.is_file(), f"{label} was not generated: {path}"
            assert_branded(path, label)

    print(f"CARBON report brand contract: PASS — {favicon_variants} HTML variants declare the self-contained cut-C favicon; 7 editorial surfaces use the full identity, custom SVG icons, and orange risk treatment")
    return 0


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