#!/usr/bin/env -S uv run --script
# /// script
# requires-python = ">=3.12"
# dependencies = []
# ///

# ─── How to run ───
# 1. Install uv: curl -LsSf https://astral.sh/uv/install.sh | sh
# 2. Use through: uv run python scripts/run_nutricoach_v140_golden_path.py --help
# ──────────────────

"""Recompute Golden Path outcomes from authoritative production artifacts."""

from __future__ import annotations

from datetime import date
from pathlib import Path
from checkin_cli.customer_coaching import load_customer_registry
from checkin_cli.store import CanonicalEventTransaction

from gateway.platforms.nutrition_weekly_owner_ledger import WeeklyGenerationLedger, WeeklyGenerationState
from gateway.platforms.nutrition_weekly_owner_model import JsonValue
from gateway.platforms.nutrition_weekly_owner_storage import bind_weekly_owner_storage
from gateway.platforms.nutrition_weekly_reminder_bootstrap import load_registered_weekly_reminder_customers
from scripts.nutricoach_v140_golden_path_models import FaultResult, ProcessEvidence
from scripts.nutricoach_v140_golden_path_profile import load_platform_config
from scripts.nutricoach_v140_golden_path_transport import read_provider_calls


def _processes(root: Path) -> list[JsonValue]:
    return [
        ProcessEvidence.model_validate_json(path.read_text(encoding="utf-8")).model_dump()
        for path in sorted((root / "processes").glob("*.json"))
    ]


def build_receipt(root: Path) -> dict[str, JsonValue]:
    """Derive every accepted count without reading a prior receipt."""
    config = load_platform_config(root)
    with load_registered_weekly_reminder_customers(config) as owned:
        rows = owned.customers[0].store.read()
    window = {date(2026, 8, 17).fromordinal(date(2026, 8, 17).toordinal() + offset) for offset in range(7)}
    by_day = {
        day: tuple(row for row in rows if row.kst_day == day)[-1]
        for day in window
    }
    states = tuple(row.state.value for row in by_day.values())
    calls = read_provider_calls(root / "provider-transcript.jsonl")
    reminders = tuple(call for call in calls if call.kind == "reminder")
    cards = tuple(call for call in calls if call.kind == "topic59_send")
    edits = tuple(call for call in calls if call.kind == "topic59_edit")
    storage = bind_weekly_owner_storage(root / "data" / "owner-actions")
    owner_rows = WeeklyGenerationLedger(storage).read_rows()
    owner_keys = {
        row.logical_key for row in owner_rows
        if row.state is WeeklyGenerationState.BOUND and row.week_start == "2026-08-17"
    }
    registry = load_customer_registry(root / "registry.json", root)
    canonical = CanonicalEventTransaction.for_customer_runtime(
        registry.customers[0]
    ).read_snapshot()
    unknown = tuple(call for call in edits if call.outcome == "unknown")
    from pydantic import TypeAdapter

    parsed_faults = TypeAdapter(list[FaultResult]).validate_json(
        (root / "fault-matrix.json").read_text(encoding="utf-8")
    )
    fault_matrix: list[JsonValue] = [
        {
            "boundary": row.boundary, "step_id": row.step_id,
            "crash_exit": row.crash_exit, "restart_exit": row.restart_exit,
            "duplicate_provider_calls": row.duplicate_provider_calls,
            "outcome": row.outcome.value,
            "evidence": [
                {
                    "source": item.source, "row_id": item.row_id,
                    "row_digest": item.row_digest, "state": item.state,
                }
                for item in row.evidence
            ],
        }
        for row in parsed_faults
    ]
    receipt: dict[str, JsonValue] = {
        "schema": "nutricoach-v140-task-10-golden-path-r3",
        "status": "PASS",
        "window": {
            "start_kst_day": "2026-08-17", "end_kst_day": "2026-08-23",
            "following_monday": "2026-08-24",
        },
        "counts": {
            "submitted": states.count("submitted"),
            "late_submitted": states.count("late_submitted"),
            "missed": states.count("missed"),
            "completed_days": states.count("submitted") + states.count("late_submitted"),
            "adherence_percent": round(
                100 * (states.count("submitted") + states.count("late_submitted")) / 7, 2
            ),
            "reminders": len(reminders), "logical_topic59_cards": len({call.kst_day for call in cards}),
            "monday_owner_cards": len(owner_keys),
            "duplicate_provider_calls": len(calls) - len({call.call_key for call in calls}),
            "automatic_customer_coaching_calls": sum(
                call.kind == "customer_coaching" for call in calls
            ),
            "privacy_leaks": sum(len(call.privacy_leak_categories) for call in calls),
        },
        "processes": _processes(root),
        "reconciliation": {
            "fault_matrix": fault_matrix,
            "cutoff_race_processes": sum(
                "wed-cutoff-race" in str(process.get("step_id", ""))
                for process in _processes(root) if isinstance(process, dict)
            ),
            "unknown_topic59_edit": {
                "provider_calls": len(unknown), "retry_count": max(0, len(edits) - 1),
                "state": "unknown" if unknown else "missing",
            },
        },
        "authority": {
            "sidecar_row_digests": [row.row_digest for row in rows],
            "canonical_event_count": len(canonical.events),
            "canonical_sequence_count": len(canonical.sequence_rows),
            "owner_generation_rows": len(owner_rows),
            "provider_call_keys": [call.call_key for call in calls],
        },
    }
    return receipt
