"""Deterministic no-network seven-day Golden Path entrypoint contract."""

from __future__ import annotations

import subprocess
from pathlib import Path
from typing import ClassVar

from pydantic import BaseModel, ConfigDict


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

    adherence_percent: float
    automatic_customer_coaching_calls: int
    completed_days: int
    duplicate_provider_calls: int
    late_submitted: int
    logical_topic59_cards: int
    missed: int
    monday_owner_cards: int
    privacy_leaks: int
    reminders: int
    submitted: int


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

    end_kst_day: str
    following_monday: str
    start_kst_day: str


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

    kst_day: str
    logical_key: str
    row_digest: str
    state: str


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

    chat_id: str
    kst_day: str
    kind: str
    message_id: str
    ordinal: int
    outcome: str
    text_sha256: str
    topic_id: str


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

    rows: list[GoldenRow]
    messages: list[GoldenMessage]


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

    provider_calls: int
    retry_count: int
    state: str


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

    unknown_topic59_edit: UnknownEdit


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

    status: str
    counts: GoldenCounts
    window: GoldenWindow
    reconciliation: GoldenReconciliation


def test_seven_day_driver_emits_exact_receipt_when_network_is_disabled(
    tmp_path: Path,
) -> None:
    # Given: a clean disposable profile root and an explicit receipt destination.
    repository = Path(__file__).resolve().parents[2]
    script = repository / "scripts" / "run_nutricoach_v140_golden_path.py"
    receipt = tmp_path / "task-10-golden-path.json"

    # When: the documented no-network weekly-operations scenario runs.
    completed = subprocess.run(
        [
            "uv",
            "run",
            "python",
            str(script),
            "--root",
            str(tmp_path / "profile"),
            "--output",
            str(receipt),
            "--manifest",
            str(tmp_path / "manifest.json"),
            "--network-disabled",
            "--skip-fault-matrix",
        ],
        cwd=repository,
        check=False,
        capture_output=True,
        text=True,
    )

    # Then: the real driver succeeds and binds the exact accepted outcomes.
    assert completed.returncode == 0, completed.stderr
    document = GoldenReceipt.model_validate_json(receipt.read_text(encoding="utf-8"))
    assert document.status == "PASS"
    assert document.counts.model_dump() == {
        "adherence_percent": 71.43,
        "automatic_customer_coaching_calls": 0,
        "completed_days": 5,
        "duplicate_provider_calls": 0,
        "late_submitted": 1,
        "logical_topic59_cards": 7,
        "missed": 2,
        "monday_owner_cards": 1,
        "privacy_leaks": 0,
        "reminders": 4,
        "submitted": 4,
    }
    assert document.window.model_dump() == {
        "end_kst_day": "2026-08-23",
        "following_monday": "2026-08-24",
        "start_kst_day": "2026-08-17",
    }
    assert document.reconciliation.unknown_topic59_edit.model_dump() == {
        "provider_calls": 1,
        "retry_count": 0,
        "state": "unknown",
    }


def test_seven_day_receipt_is_byte_identical_across_clean_roots(tmp_path: Path) -> None:
    # Given: two independent clean disposable profile roots.
    repository = Path(__file__).resolve().parents[2]
    script = repository / "scripts" / "run_nutricoach_v140_golden_path.py"
    receipts: list[str] = []

    # When: the production Golden Path is replayed from each clean root.
    for ordinal in (1, 2):
        output = tmp_path / f"receipt-{ordinal}.json"
        completed = subprocess.run(
            [
                "uv", "run", "python", str(script),
                "--root", str(tmp_path / f"profile-{ordinal}"),
                "--output", str(output),
                "--manifest", str(tmp_path / f"manifest-{ordinal}.json"),
                "--network-disabled", "--skip-fault-matrix",
            ],
            cwd=repository,
            check=False,
            capture_output=True,
            text=True,
        )
        assert completed.returncode == 0, completed.stderr
        normalized = GoldenReceipt.model_validate_json(output.read_text(encoding="utf-8"))
        receipts.append(normalized.model_dump_json())

    # Then: normalized evidence is byte-identical, not merely count-equivalent.
    assert receipts[0] == receipts[1]


def test_seven_day_driver_rejects_network_enabled_surface(tmp_path: Path) -> None:
    # Given: the Golden Path entrypoint without its mandatory network fence.
    repository = Path(__file__).resolve().parents[2]
    script = repository / "scripts" / "run_nutricoach_v140_golden_path.py"

    # When: the caller omits --network-disabled.
    completed = subprocess.run(
        [
            "uv", "run", "python", str(script),
            "--root", str(tmp_path / "profile"),
        ],
        cwd=repository,
        check=False,
        capture_output=True,
        text=True,
    )

    # Then: validation fails before a profile or provider can be touched.
    assert completed.returncode == 2
    assert "--network-disabled" in completed.stderr
    assert not (tmp_path / "profile").exists()
