#!/usr/bin/env python3
"""Verify CARBON's anonymous, balanced, repeatable-evidence testing doctrine."""

from __future__ import annotations

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


PLUGIN = Path(__file__).resolve().parents[1]
REFERENCE = PLUGIN / "runtime" / "carbon" / "references" / "testing-doctrine.json"
GUIDE = PLUGIN / "runtime" / "carbon" / "references" / "testing-doctrine.md"
WORKSPACE = PLUGIN / "runtime" / "carbon" / "scripts" / "carbon_workspace.py"
FRAMEWORK = PLUGIN / "runtime" / "carbon" / "scripts" / "carbon_framework.py"


def command(*args: str) -> dict:
    result = subprocess.run(args, cwd=PLUGIN, text=True, capture_output=True, check=False)
    if result.returncode:
        raise AssertionError(result.stderr or result.stdout)
    return json.loads(result.stdout)


def main() -> int:
    doctrine = json.loads(REFERENCE.read_text(encoding="utf-8"))
    guide = GUIDE.read_text(encoding="utf-8")
    combined = f"{REFERENCE.read_text(encoding='utf-8')}\n{guide}".lower()

    assert doctrine["schema"] == "carbon.testing-doctrine/v1"
    assert doctrine["version"] == "1.0.0"
    assert not re.search(r"\bjason\b|\barbon\b", combined)
    assert "anonymous" in doctrine["identityBoundary"].lower()
    assert len(doctrine["principles"]) >= 10
    assert len(doctrine["spices"]) >= 12
    assert len(doctrine["decisionRules"]) >= 6
    assert len(doctrine["antiPatterns"]) >= 8
    assert len({row["id"] for row in doctrine["principles"]}) == len(doctrine["principles"])
    assert len({row["id"] for row in doctrine["spices"]}) == len(doctrine["spices"])
    for spice in doctrine["spices"]:
        for field in ("practice", "pro", "con", "carbonDefault"):
            assert spice.get(field), f"{spice.get('id')} is missing {field}"

    rapid = next(row for row in doctrine["spices"] if row["id"] == "rapid-and-session-based-exploration")
    assert "learning" in rapid["pro"].lower()
    assert "person-dependent" in rapid["con"].lower()
    assert "repeatable candidates" in rapid["carbonDefault"].lower()
    assert "never treat an exploratory session alone" in rapid["carbonDefault"].lower()

    with tempfile.TemporaryDirectory(prefix="carbon-doctrine-") as temporary:
        root = Path(temporary)
        (root / "src").mkdir()
        (root / "src" / "app.py").write_text("def status(): return 'ok'\n", encoding="utf-8")

        workspace = command(
            sys.executable, str(WORKSPACE), "inspect", "--root", str(root), "--max-files", "500",
        )
        judgment = workspace["professionalJudgment"]
        assert judgment["schema"] == doctrine["schema"]
        assert judgment["version"] == doctrine["version"]
        assert len(judgment["practiceBalances"]) == len(doctrine["spices"])
        assert "naming" in judgment["identityBoundary"].lower()

        prepared = command(
            sys.executable, str(FRAMEWORK), "prepare", "--root", str(root),
            "--request", "test this", "--size", "quick",
        )
        plan = json.loads(
            (root / ".carbon" / "framework" / "orchestration-plan.json").read_text(encoding="utf-8")
        )
        assert prepared["testingDoctrineVersion"] == doctrine["version"]
        assert plan["testingDoctrine"]["version"] == doctrine["version"]
        assert "rapid-and-session-based-exploration" in plan["testingDoctrine"]["practiceBalances"]
        assert "discovery is not trusted regression evidence" in plan["testingDoctrine"]["rule"]

    server = (PLUGIN / "server" / "index.js").read_text(encoding="utf-8")
    assert "testingDoctrinePromptAppendix" in server
    assert "For every selected practice" in server
    assert "never count the session alone as regression or release proof" in server

    print("PASS: anonymous doctrine, pro/con spices, exploration caution, and repeatable-evidence planning verified.")
    return 0


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