#!/usr/bin/env python3
"""Contract-test the recoverable modernization of early CARBON report output."""

from __future__ import annotations

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


ROOT = Path(__file__).resolve().parents[1]
RUNTIME = ROOT / "runtime" / "carbon" / "scripts"
MIGRATOR = RUNTIME / "carbon_historical_report_migration.py"


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


def old_report(name: str) -> str:
    return f'''<!doctype html><html><head><title>{name}</title></head><body>
<header>CARBON</header><section class="specialist-section"><article class="specialist-card">Every old specialist</article></section>
<section class="visual-section" aria-label="Activity visualizations">NOT MEASURED</section>
</body></html>'''


def main() -> int:
    with tempfile.TemporaryDirectory(prefix="carbon-historical-report-") as temporary:
        project = Path(temporary)
        reports = project / ".carbon" / "reports" / "commands"
        reports.mkdir(parents=True)
        files = {
            "20260815T005557Z-carbon-f77c.html": old_report("First Look"),
            "20260817T055945Z-carbon-stats-3965.html": old_report("stats"),
            "20260820T074126Z-carbon-privacy-e2c1.html": old_report("privacy"),
            "20260815T005557Z-wcag-2-2-5b38.html": old_report("wcag"),
            "20260815T005557Z-accessibility-conformance-report-c1a8.html": old_report("acr"),
        }
        for name, source in files.items():
            (reports / name).write_text(source, encoding="utf-8")

        preview = run("--root", str(project))
        assert preview["applied"] is False and len(preview["changes"]) == 5
        applied = run("--root", str(project), "--apply")
        backup = Path(str(applied["backupDir"]))
        assert backup.is_dir() and len(applied["changes"]) == 5
        assert len(list(backup.glob("*.html"))) == 5

        first = (reports / "20260815T005557Z-carbon-f77c.html").read_text(encoding="utf-8")
        stats = (reports / "20260817T055945Z-carbon-stats-3965.html").read_text(encoding="utf-8")
        privacy = (reports / "20260820T074126Z-carbon-privacy-e2c1.html").read_text(encoding="utf-8")
        wcag = (reports / "20260815T005557Z-wcag-2-2-5b38.html").read_text(encoding="utf-8")
        acr = (reports / "20260815T005557Z-accessibility-conformance-report-c1a8.html").read_text(encoding="utf-8")
        for source in (first, stats, privacy, wcag, acr):
            assert "carbon-historical-modernization" in source
            assert source.count('class="specialist-card"') == 1
            assert source.count('class="specialist-ai-badge"') == 1
            assert "NOT MEASURED" not in source and "NOT ESTIMATED" not in source
        assert "Yuki" in first and "Pete" in privacy and "Jason" in stats
        assert "Criterion evidence was not captured" in wcag and "Criterion evidence was not captured" in acr
        assert run("--root", str(project))["changes"] == []

    print("PASS: legacy CARBON report modernization is recoverable, profile-scoped, avoids empty telemetry cards, and replaces empty accessibility scaffolds with an evidence-required notice.")
    return 0


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