"""
AI Agent owner-approved learning dry-run snapshot.

Loads the latest committed P2-403F dry-run contract for owner-approved
learning writeback previews. This module never writes KM, updates PlayBook
trust, writes timeline learning, sends Telegram messages, or starts workers.
"""

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 = "ai_agent_owner_approved_learning_dry_run_*.json"
_SCHEMA_VERSION = "ai_agent_owner_approved_learning_dry_run_v1"


def load_latest_ai_agent_owner_approved_learning_dry_run(
    evaluations_dir: Path | None = None,
) -> dict[str, Any]:
    """Load the newest committed AI Agent owner-approved learning dry-run contract."""
    directory = evaluations_dir or _DEFAULT_EVALUATIONS_DIR
    candidates = sorted(directory.glob(_SNAPSHOT_PATTERN))
    if not candidates:
        raise FileNotFoundError(
            f"no AI Agent owner-approved learning dry-run 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, str(latest))
    _require_read_only_boundaries(payload, str(latest))
    _require_preview_safety(payload, str(latest))
    _require_rollup_consistency(payload, str(latest))
    return payload


def _require_schema(payload: dict[str, Any], label: str) -> None:
    actual = payload.get("schema_version")
    if actual != _SCHEMA_VERSION:
        raise ValueError(f"{label}: expected schema_version={_SCHEMA_VERSION}, got {actual!r}")
    status = payload.get("program_status") or {}
    if status.get("read_only_mode") is not True:
        raise ValueError(f"{label}: program_status.read_only_mode must be true")
    if status.get("runtime_authority") != "owner_approved_dry_run_only_no_learning_write":
        raise ValueError(f"{label}: runtime_authority must stay owner_approved_dry_run_only_no_learning_write")


def _require_read_only_boundaries(payload: dict[str, Any], label: str) -> None:
    boundaries = payload.get("approval_boundaries") or {}
    enabled = sorted(key for key, value in boundaries.items() if value is not False)
    if enabled:
        raise ValueError(f"{label}: approval boundaries must remain false: {enabled}")

    truth = payload.get("dry_run_truth") or {}
    if truth.get("owner_approval_required") is not True:
        raise ValueError(f"{label}: owner approval must remain required")
    if truth.get("dry_run_preview_allowed") is not True:
        raise ValueError(f"{label}: dry-run preview contract must remain allowed")

    false_flags = {
        "km_write_allowed",
        "playbook_trust_write_allowed",
        "timeline_learning_write_allowed",
        "agent_replay_score_write_allowed",
        "telegram_send_allowed",
        "runtime_worker_allowed",
    }
    unsafe = sorted(flag for flag in false_flags if truth.get(flag) is not False)
    if unsafe:
        raise ValueError(f"{label}: learning write flags must remain false: {unsafe}")

    zero_counts = {
        "owner_approval_received_count",
        "dry_run_preview_generated_count",
    }
    non_zero = sorted(key for key in zero_counts if truth.get(key) != 0)
    if non_zero:
        raise ValueError(f"{label}: owner approval and dry-run generated counts must remain zero: {non_zero}")


def _require_preview_safety(payload: dict[str, Any], label: str) -> None:
    preview = payload.get("dry_run_preview") or {}
    required_inputs = set(preview.get("required_inputs") or [])
    required_minimum = {
        "owner_approval_id",
        "incident_id",
        "redacted_evidence_refs",
        "target_learning_surface",
        "rollback_plan_ref",
        "verification_plan_ref",
    }
    missing = sorted(required_minimum - required_inputs)
    if missing:
        raise ValueError(f"{label}: dry-run preview missing required inputs: {missing}")
    if not preview.get("preview_outputs"):
        raise ValueError(f"{label}: dry-run preview outputs must not be empty")

    actions = payload.get("operator_actions") or []
    action_types = {action.get("action_type") for action in actions}
    required_actions = {"review", "collect_evidence", "approve_dry_run", "reject_or_rework"}
    if not required_actions.issubset(action_types):
        raise ValueError(f"{label}: operator actions must cover {sorted(required_actions)}")

    verification = payload.get("verification_contract") or {}
    if verification.get("verification_required") is not True:
        raise ValueError(f"{label}: verification must be required")
    if verification.get("rollback_required") is not True:
        raise ValueError(f"{label}: rollback must be required")
    if not verification.get("verification_steps"):
        raise ValueError(f"{label}: verification steps must not be empty")

    redaction = payload.get("display_redaction_contract") or {}
    if redaction.get("redaction_required") is not True:
        raise ValueError(f"{label}: frontend redaction must be required")
    for flag in ("raw_payload_display_allowed", "private_reasoning_display_allowed", "secret_value_display_allowed"):
        if redaction.get(flag) is not False:
            raise ValueError(f"{label}: {flag} must remain false")


def _require_rollup_consistency(payload: dict[str, Any], label: str) -> None:
    rollups = payload.get("rollups") or {}
    actions = payload.get("operator_actions") or []
    gates = payload.get("dry_run_gates") or []
    preview = payload.get("dry_run_preview") or {}
    truth = payload.get("dry_run_truth") or {}
    expected_counts = {
        "operator_action_count": len(actions),
        "dry_run_gate_count": len(gates),
        "blocked_write_action_count": len({gate.get("blocked_write_action") for gate in gates}),
        "required_input_count": len(preview.get("required_inputs") or []),
        "forbidden_input_count": len(preview.get("forbidden_inputs") or []),
        "preview_output_count": len(preview.get("preview_outputs") or []),
    }
    mismatched = {
        key: {"expected": expected, "actual": rollups.get(key)}
        for key, expected in expected_counts.items()
        if rollups.get(key) != expected
    }
    if mismatched:
        raise ValueError(f"{label}: rollup counts must match payload sections: {mismatched}")

    approval_required = sorted(
        gate.get("gate_id") for gate in gates if gate.get("status") == "approval_required"
    )
    if sorted(rollups.get("approval_required_gate_ids") or []) != approval_required:
        raise ValueError(f"{label}: rollups.approval_required_gate_ids mismatch")
    if rollups.get("live_write_count_total") != 0:
        raise ValueError(f"{label}: live write count must remain zero")
    if rollups.get("dry_run_preview_generated_count") != truth.get("dry_run_preview_generated_count"):
        raise ValueError(f"{label}: dry_run_preview_generated_count mismatch")
