"""
Offsite / escrow readiness status snapshot.

Loads the latest committed, read-only offsite / escrow readiness status. The
status view never runs backups, restores, offsite sync, credential marker
writes, credential reads, schedule changes, workflow writes, Telegram test
notifications, destructive prune, or production routing changes.
"""

from __future__ import annotations

import json
from pathlib import Path
from typing import Any

from src.services.snapshot_paths import default_evaluations_dir

_DEFAULT_EVALUATIONS_DIR = default_evaluations_dir(Path(__file__))
_SNAPSHOT_PATTERN = "offsite_escrow_readiness_status_*.json"
_SCHEMA_VERSION = "offsite_escrow_readiness_status_v1"


def load_latest_offsite_escrow_readiness_status(
    evaluations_dir: Path | None = None,
) -> dict[str, Any]:
    """Load the newest committed offsite / escrow readiness status snapshot."""
    directory = evaluations_dir or _DEFAULT_EVALUATIONS_DIR
    candidates = sorted(directory.glob(_SNAPSHOT_PATTERN))
    if not candidates:
        raise FileNotFoundError(f"no offsite / escrow readiness status snapshots found in {directory}")

    latest = candidates[-1]
    with latest.open(encoding="utf-8") as handle:
        payload = json.load(handle)

    if not isinstance(payload, dict):
        raise ValueError(f"{latest}: expected JSON object")
    _require_schema(payload, _SCHEMA_VERSION, str(latest))
    _require_read_only_boundaries(payload, str(latest))
    _require_operation_boundaries(payload, str(latest))
    _require_rollup_consistency(payload, str(latest))
    _require_redacted_cards(payload, str(latest))
    return payload


def _require_schema(payload: dict[str, Any], expected: str, label: str) -> None:
    actual = payload.get("schema_version")
    if actual != expected:
        raise ValueError(f"{label}: expected schema_version={expected}, got {actual!r}")


def _require_read_only_boundaries(payload: dict[str, Any], label: str) -> None:
    program_status = payload.get("program_status") or {}
    if program_status.get("read_only_mode") is not True:
        raise ValueError(f"{label}: program_status.read_only_mode must be true")

    boundaries = payload.get("approval_boundaries") or {}
    blocked_flags = {
        "sdk_installation_allowed",
        "paid_api_call_allowed",
        "shadow_or_canary_allowed",
        "production_routing_allowed",
        "destructive_operation_allowed",
        "restore_execution_allowed",
        "offsite_sync_execution_allowed",
        "credential_marker_write_allowed",
    }
    allowed = sorted(flag for flag in blocked_flags if boundaries.get(flag) is not False)
    if allowed:
        raise ValueError(f"{label}: approval boundaries must remain false: {allowed}")


def _require_operation_boundaries(payload: dict[str, Any], label: str) -> None:
    boundaries = payload.get("operation_boundaries") or {}
    if boundaries.get("read_only_status_allowed") is not True:
        raise ValueError(f"{label}: read_only_status_allowed must be true")

    blocked_flags = {
        "backup_execution_allowed",
        "restore_execution_allowed",
        "offsite_sync_execution_allowed",
        "credential_marker_write_allowed",
        "credential_read_allowed",
        "secret_plaintext_allowed",
        "schedule_change_allowed",
        "workflow_write_allowed",
        "telegram_test_notification_allowed",
        "destructive_prune_allowed",
        "production_routing_allowed",
    }
    allowed = sorted(flag for flag in blocked_flags if boundaries.get(flag) is not False)
    if allowed:
        raise ValueError(f"{label}: operation boundaries must remain false: {allowed}")


def _require_rollup_consistency(payload: dict[str, Any], label: str) -> None:
    cards = payload.get("readiness_cards") or []
    rollups = payload.get("rollups") or {}
    if rollups.get("total_cards") != len(cards):
        raise ValueError(f"{label}: rollups.total_cards must match readiness_cards")

    verified_offsite = {
        card.get("card_id")
        for card in cards
        if card.get("kind") == "offsite_mirror" and card.get("readiness") == "verified"
    }
    if set(rollups.get("verified_offsite_card_ids") or []) != verified_offsite:
        raise ValueError(f"{label}: rollups.verified_offsite_card_ids must match verified offsite cards")

    blocked_escrow = {
        card.get("card_id")
        for card in cards
        if card.get("kind") == "credential_escrow" and card.get("readiness") == "blocked"
    }
    if set(rollups.get("blocked_escrow_card_ids") or []) != blocked_escrow:
        raise ValueError(f"{label}: rollups.blocked_escrow_card_ids must match blocked escrow cards")

    action_required = {
        card.get("card_id")
        for card in cards
        if card.get("readiness") == "action_required"
    }
    if set(rollups.get("action_required_card_ids") or []) != action_required:
        raise ValueError(f"{label}: rollups.action_required_card_ids must match action_required cards")

    execution_blocked = {
        card.get("card_id")
        for card in cards
        if any(operation.endswith("_execution") or operation == "credential_marker_write" for operation in card.get("blocked_operations", []))
    }
    if set(rollups.get("execution_blocked_card_ids") or []) != execution_blocked:
        raise ValueError(f"{label}: rollups.execution_blocked_card_ids must match cards with blocked execution operations")


def _require_redacted_cards(payload: dict[str, Any], label: str) -> None:
    cards = payload.get("readiness_cards") or []
    forbidden_exposure = {
        "plaintext",
        "secret_plaintext",
        "credential_plaintext",
        "token_visible",
    }
    exposed = sorted(
        card.get("card_id")
        for card in cards
        if card.get("credential_exposure_status") in forbidden_exposure
    )
    if exposed:
        raise ValueError(f"{label}: credential exposure must stay redacted: {exposed}")

    contract = payload.get("operator_contract") or {}
    must_not_interpret_as = set(contract.get("must_not_interpret_as") or [])
    required_denials = {
        "復原批准",
        "異地同步批准",
        "credential marker 寫入批准",
        "完整 DR 綠燈",
    }
    if not required_denials.issubset(must_not_interpret_as):
        raise ValueError(f"{label}: operator_contract.must_not_interpret_as is missing required denials")
