"""Todo10 r3 derived fault and rendered-text privacy contracts."""

from __future__ import annotations

import subprocess
from pathlib import Path

from scripts.nutricoach_v140_golden_path_models import FaultOutcome, FaultResult
from scripts.nutricoach_v140_golden_path_privacy import SENTINELS, scan_provider_text
from scripts.nutricoach_v140_golden_path_transport import read_provider_calls

REPOSITORY = Path(__file__).resolve().parents[2]
ENTRYPOINT = REPOSITORY / "scripts" / "run_nutricoach_v140_golden_path.py"


def _run(*arguments: str) -> subprocess.CompletedProcess[str]:
    return subprocess.run(
        ["uv", "run", "--offline", "python", "-B", str(ENTRYPOINT), *arguments],
        cwd=REPOSITORY, check=False, capture_output=True, text=True,
    )


def test_fault_results_are_exhaustive_and_bind_authoritative_rows(tmp_path: Path) -> None:
    root, receipt = tmp_path / "profile", tmp_path / "receipt.json"
    completed = _run(
        "--root", str(root), "--output", str(receipt),
        "--manifest", str(tmp_path / "manifest.json"), "--network-disabled",
    )
    assert completed.returncode == 0, completed.stderr
    from pydantic import TypeAdapter

    results = TypeAdapter(list[FaultResult]).validate_json(
        (root / "fault-matrix.json").read_text(encoding="utf-8")
    )
    assert len(results) == 12
    assert {row.outcome for row in results} == {
        FaultOutcome.RECONCILED_SUCCESS, FaultOutcome.TERMINAL_UNKNOWN,
    }
    assert all(row.evidence and row.duplicate_provider_calls == 0 for row in results)
    assert all(item.row_id and item.row_digest and item.state for row in results for item in row.evidence)


def test_sentinel_render_produces_positive_scan_and_fails_artifact_verification(
    tmp_path: Path,
) -> None:
    root, receipt, manifest = tmp_path / "profile", tmp_path / "receipt.json", tmp_path / "manifest.json"
    generated = _run(
        "--root", str(root), "--output", str(receipt), "--manifest", str(manifest),
        "--network-disabled", "--skip-fault-matrix",
    )
    assert generated.returncode == 0, generated.stderr
    text = f"negative fixture {SENTINELS['free_text']}"
    assert scan_provider_text("generic_schedule", text).leak_count > 0
    injected = _run("--privacy-negative", "--root", str(root))
    assert injected.returncode == 0, injected.stderr
    calls = read_provider_calls(root / "provider-transcript.jsonl")
    assert sum(len(call.privacy_leak_categories) for call in calls) > 0
    checked = _run(
        "--verify", "--root", str(root), "--receipt", str(receipt),
        "--manifest", str(manifest),
    )
    assert checked.returncode == 1
    assert "privacy" in checked.stderr