#!/usr/bin/env python3
"""Contract coverage for CARBON's privacy-safe activity statistics."""

from __future__ import annotations

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


ROOT = Path(__file__).resolve().parent.parent
SCRIPT = ROOT / "runtime" / "carbon" / "scripts" / "carbon_stats.py"


def run(*arguments: str, ok: bool = True) -> dict:
    completed = subprocess.run([sys.executable, str(SCRIPT), *arguments], capture_output=True, text=True)
    if ok:
        assert completed.returncode == 0, completed.stderr
        return json.loads(completed.stdout)
    assert completed.returncode != 0
    return {"stderr": completed.stderr}


def write_json(path: Path, value: dict) -> None:
    path.parent.mkdir(parents=True, exist_ok=True)
    path.write_text(json.dumps(value), encoding="utf-8")


def main() -> int:
    with tempfile.TemporaryDirectory(prefix="carbon-stats-") as temporary:
        project = Path(temporary)
        reports = project / ".carbon" / "reports" / "commands"
        reports.mkdir(parents=True)
        for name in (
            "20260810T010000Z-carbon-help-ab12.html",
            "20260810T020000Z-carbon-help-cd34.html",
            "20260810T030000Z-carbon-test-ef56.html",
            "20260810T040000Z-wcag-2-2-abcd.html",
        ):
            (reports / name).write_text("<!doctype html>", encoding="utf-8")
        write_json(project / ".carbon" / "workspace" / "journey.json", {
            "schema": "carbon.workspace-journey/v1",
            "commands": {"carbon-help": {"count": 3, "firstRunAt": "2026-08-08T00:00:00Z", "lastRunAt": "2026-08-10T00:00:00Z"}},
        })
        write_json(project / ".carbon" / "tests" / "intent-tests.json", {"tests": [{"id": "I-1"}]})
        write_json(project / ".carbon" / "framework" / "regression-suite.json", {"tests": [{"id": "R-1"}]})
        run_dir = project / ".carbon" / "runs" / "RUN-1"
        write_json(run_dir / "run.json", {
            "runId": "RUN-1", "status": "completed", "startedAt": "2026-08-10T00:00:00Z", "finishedAt": "2026-08-10T00:03:00Z",
            "tests": [
                {"id": "T-1", "status": "passed", "attempts": 1},
                {"id": "T-2", "status": "failed", "attempts": 1},
                {"id": "T-3", "status": "blocked", "attempts": 0},
            ],
            "findings": [{"id": "F-1", "severity": "high", "title": "Checkout total changed after retry"}],
        })
        write_json(run_dir / "evidence" / "manifest.json", {
            "pages": [{"artifacts": [{"channel": "screenshot"}, {"channel": "network"}]}],
            "issues": [{"id": "SIG-1", "severity": "low", "title": "Evidence redacted", "confidence": "observed"}],
        })
        # Synthetic benchmark findings never enter project issue totals.
        write_json(project / ".carbon" / "benchmarks" / "runs" / "B-1" / "result.json", {
            "issues": [{"id": "SEED", "severity": "critical", "title": "Seeded only"}],
        })

        subscription_result = run("summary", "--root", str(project), "--no-record-current-command")
        subscription_payload = subscription_result["reportPayload"]
        assert subscription_result["usage"]["tokensMeasured"] is False
        assert all("token" not in metric["label"].lower() and "cost" not in metric["label"].lower() for metric in subscription_payload["metrics"])
        assert all("token" not in section["title"].lower() and "model" not in section["title"].lower() and "economics" not in section["title"].lower() for section in subscription_payload["sections"])
        assert not subscription_payload["statsVisuals"]["activity"]
        assert "No exact host usage records:" not in json.dumps(subscription_payload)
        assert "Total tokens" not in json.dumps(subscription_payload)

        rejected = run("record-fix", "--root", str(project), "--finding-id", "F-1", "--run-id", "RUN-1", ok=False)
        assert "explicit verification" in rejected["stderr"]
        unknown = run("record-fix", "--root", str(project), "--finding-id", "MISSING", "--run-id", "RUN-1", "--verified", ok=False)
        assert "exactly one available" in unknown["stderr"]
        negative = run("record-usage", "--root", str(project), "--activity", "execution", "--total-tokens", "-1", ok=False)
        assert "cannot be negative" in negative["stderr"]
        run("record-fix", "--root", str(project), "--finding-id", "F-1", "--run-id", "RUN-1", "--verified", "--verification", "targeted re-test")
        run("record-usage", "--root", str(project), "--activity", "planning", "--command", "carbon-test", "--provider", "openai", "--model", "gpt-example", "--model-level", "high", "--input-tokens", "100", "--output-tokens", "50", "--total-tokens", "150", "--cost-usd", "0.01", "--duration-seconds", "20")
        run("record-usage", "--root", str(project), "--activity", "test-creation", "--model", "gpt-example", "--total-tokens", "300", "--cost-usd", "0.06", "--tests-created", "2", "--duration-seconds", "30")
        run("record-usage", "--root", str(project), "--activity", "execution", "--model", "gpt-example", "--total-tokens", "450", "--cost-usd", "0.09", "--tests-executed", "3", "--issues-found", "1", "--duration-seconds", "120")

        baseline = json.dumps({
            "manualTestCreationMinutes": 10,
            "manualTestExecutionMinutes": 5,
            "manualIssueTriageMinutes": 20,
            "manualFixVerificationMinutes": 10,
            "loadedHourlyRateUsd": 90,
        })
        assert run("configure", "--root", str(project), "--baseline-json", baseline, ok=False)["stderr"]
        configured = run("configure", "--root", str(project), "--baseline-json", baseline, "--confirm")
        assert configured["configured"] is True

        result = run("summary", "--root", str(project), "--no-record-current-command")
        assert result["schema"] == "carbon.stats/v1"
        assert result["commands"]["total"] == 4 and result["commands"]["top"] == {"command": "carbon-help", "count": 3}
        assert result["testsCreated"]["total"] == 2
        assert result["runs"]["tests"]["executed"] == 3
        assert result["issues"]["found"] == 1 and result["issues"]["fixed"] == 1
        assert result["runs"]["signals"] == 1
        assert result["issues"]["biggestFixed"][0]["title"] == "Checkout total changed after retry"
        assert result["usage"]["tokens"]["totalTokens"] == 900
        assert result["usage"]["models"][0]["model"] == "gpt-example"
        assert result["usage"]["totalCostUsd"] == 0.16
        assert result["unitEconomics"]["costPerTestCreatedUsd"] == 0.03
        assert result["unitEconomics"]["costPerTestExecutedUsd"] == 0.03
        assert result["savings"]["available"] is True and result["savings"]["label"] == "SCENARIO ESTIMATE"
        assert result["funStats"]["evidenceDensity"] == "0.7 artifacts per executed test"
        assert result["reportPayload"]["command"] == "carbon-stats"
        assert result["reportPayload"]["decision"]["label"] == "ACTIVITY"
        assert len(result["reportPayload"]["narrative"]) == 5
        assert result["reportPayload"]["statsVisuals"]["activity"]
        assert result["reportPayload"]["statsVisuals"]["commands"][0]["label"] == "/carbon-help"
        assert result["reportPayload"]["statsVisuals"]["issues"][0]["value"] == 1
        assert result["reportPayload"]["statsVisuals"]["economics"]
        assert "confirmed findings" in result["reportPayload"]["summary"]
        sections = result["reportPayload"]["sections"]
        assert all(item.get("status") for section in sections if "items" in section for item in section["items"])
        assert "Total tokens" in [metric["label"] for metric in result["reportPayload"]["metrics"]]
        assert {"Where the tokens went", "Models and levels", "Unit economics"}.issubset({section["title"] for section in sections})
        assert "NOT MEASURED" not in json.dumps(result["reportPayload"])

        ledger = (project / ".carbon" / "stats" / "events.jsonl").read_text(encoding="utf-8")
        for private_value in ("Checkout total", "https://", "prompt", "credential"):
            assert private_value not in ledger
        assert (project / ".carbon" / "stats" / "events.jsonl").stat().st_mode & 0o777 == 0o600

    print("PASS: CARBON stats aggregates observed activity, excludes seeded defects, records content-free exact usage, verifies fixes, labels scenario savings, and prepares a branded report payload.")
    return 0


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