"""Todo10 r2 production-path and completed-artifact verification contracts."""

from __future__ import annotations

import ast
import subprocess
from pathlib import Path

from pydantic import BaseModel, ConfigDict
from typing import ClassVar


class RestartProcess(BaseModel):
    model_config: ClassVar[ConfigDict] = ConfigDict(frozen=True)

    pid: int
    start_epoch_ns: int
    reopened_authoritative_stores: bool


class RestartReceipt(BaseModel):
    model_config: ClassVar[ConfigDict] = ConfigDict(frozen=True)

    processes: list[RestartProcess]


class FaultResult(BaseModel):
    model_config: ClassVar[ConfigDict] = ConfigDict(frozen=True)

    boundary: str
    crash_exit: int
    restart_exit: int
    duplicate_provider_calls: int


class FaultReconciliation(BaseModel):
    model_config: ClassVar[ConfigDict] = ConfigDict(frozen=True)

    fault_matrix: list[FaultResult]
    cutoff_race_processes: int


class FaultReceipt(BaseModel):
    model_config: ClassVar[ConfigDict] = ConfigDict(frozen=True)

    reconciliation: FaultReconciliation


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_driver_has_no_test_imports_when_production_path_is_required() -> None:
    # Given: every Python member loaded by the Todo10 entrypoint.
    members = tuple((REPOSITORY / "scripts").glob("*nutricoach_v140_golden_path*.py"))

    # When: import declarations are parsed structurally.
    imported = {
        alias.name
        for member in members
        for node in ast.walk(ast.parse(member.read_text(encoding="utf-8")))
        if isinstance(node, ast.Import)
        for alias in node.names
    } | {
        node.module or ""
        for member in members
        for node in ast.walk(ast.parse(member.read_text(encoding="utf-8")))
        if isinstance(node, ast.ImportFrom)
    }

    # Then: no test fixture or support package participates in production proof.
    assert not {name for name in imported if name == "tests" or name.startswith("tests.")}


def test_driver_uses_production_tick_without_constructing_schedule_tasks() -> None:
    # Given: the complete Todo10 driver source graph.
    source = "\n".join(
        member.read_text(encoding="utf-8")
        for member in (REPOSITORY / "scripts").glob("*nutricoach_v140_golden_path*.py")
    )

    # When: the orchestration seam is inspected.
    production_tick = "_send_nutrition_coaching_tick_authorized" in source

    # Then: eligibility belongs to production scheduling, never a constructed task.
    assert production_tick
    assert "CustomerScheduleTask(" not in source


def test_completed_artifact_verifier_rejects_each_tamper_class(tmp_path: Path) -> None:
    # Given: one completed no-network production scenario.
    root = tmp_path / "profile"
    receipt = tmp_path / "receipt.json"
    manifest = 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

    # When: each independently meaningful artifact class is tampered.
    mutations = {
        "row_state": (root / "weekly-authority", b'"state":"submitted"'),
        "message_id": (root / "provider-transcript.jsonl", b'"message_id":"'),
        "source_byte": (root / "data" / "customers", b"event_id"),
        "manifest_member": (manifest, b'"path":"'),
    }
    for name, (target, needle) in mutations.items():
        pattern = "*day-status-v1.jsonl" if name == "row_state" else "*.jsonl"
        candidate = next(target.rglob(pattern)) if target.is_dir() else target
        original = candidate.read_bytes()
        assert needle in original, name
        _ = candidate.write_bytes(original.replace(needle, needle + b"tampered-", 1))

        # Then: verification reaches artifact logic and names the mismatch.
        checked = _run(
            "--verify", "--receipt", str(receipt), "--manifest", str(manifest),
            "--root", str(root),
        )
        assert checked.returncode == 1, (name, checked.stderr)
        assert "mismatch" in checked.stderr and "unrecognized" not in checked.stderr
        _ = candidate.write_bytes(original)


def test_fault_matrix_executes_every_observed_weekly_boundary(tmp_path: Path) -> None:
    # Given: one full production scenario with fault qualification enabled.
    receipt = tmp_path / "receipt.json"

    # When: every observed weekly append/fsync/provider seam is replayed.
    completed = _run(
        "--root", str(tmp_path / "profile"), "--output", str(receipt),
        "--manifest", str(tmp_path / "manifest.json"), "--network-disabled",
    )

    # Then: each injected child exits at the seam and its fresh restart reconciles.
    assert completed.returncode == 0, completed.stderr
    document = FaultReceipt.model_validate_json(receipt.read_text(encoding="utf-8"))
    matrix = document.reconciliation.fault_matrix
    assert len(matrix) >= 10
    assert document.reconciliation.cutoff_race_processes == 2
    assert all(row.crash_exit == 86 and row.restart_exit == 0 for row in matrix)
    assert all(row.duplicate_provider_calls == 0 for row in matrix)


def test_receipt_records_observed_fresh_child_restarts(tmp_path: Path) -> None:
    # Given: a clean seven-day root.
    receipt = tmp_path / "receipt.json"

    # When: the orchestrator runs every scenario step in fresh children.
    completed = _run(
        "--root", str(tmp_path / "profile"), "--output", str(receipt),
        "--manifest", str(tmp_path / "manifest.json"), "--network-disabled",
        "--skip-fault-matrix",
    )
    assert completed.returncode == 0, completed.stderr
    document = RestartReceipt.model_validate_json(receipt.read_text(encoding="utf-8"))
    processes = document.processes

    # Then: restart evidence is observed process identity, not a declared count.
    pids = [process.pid for process in processes]
    assert len(pids) >= 8
    assert len(set(pids)) == len(pids)
    assert all(process.start_epoch_ns > 0 for process in processes)
    assert all(process.reopened_authoritative_stores is True for process in processes[1:])
