"""
AI Agent critic / reviewer result capture snapshot.

Loads the latest committed P2-105 critic / reviewer score and result capture
contract. This module validates repo-committed evidence only; it never writes
learning state, updates PlayBook trust, writes KM / LOGBOOK / audit / timeline,
writes Gateway queues, sends Telegram messages, reads secrets, or starts runtime
work.
"""

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_critic_reviewer_result_capture_*.json"
_SCHEMA_VERSION = "ai_agent_critic_reviewer_result_capture_v1"
_RUNTIME_AUTHORITY = "critic_reviewer_result_capture_contract_only_no_live_write"


def load_latest_ai_agent_critic_reviewer_result_capture(
    evaluations_dir: Path | None = None,
) -> dict[str, Any]:
    """Load the newest committed critic / reviewer result capture contract."""
    directory = evaluations_dir or _DEFAULT_EVALUATIONS_DIR
    candidates = sorted(directory.glob(_SNAPSHOT_PATTERN))
    if not candidates:
        raise FileNotFoundError(f"no AI Agent critic / reviewer result capture 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_prior_readback(payload, str(latest))
    _require_score_truth(payload, str(latest))
    _require_scorecards(payload, str(latest))
    _require_result_capture_contracts(payload, str(latest))
    _require_promotion_gates(payload, str(latest))
    _require_candidate_routes(payload, str(latest))
    _require_redaction_contract(payload, str(latest))
    _require_no_forbidden_display_terms(payload, str(latest))
    _require_rollup_consistency(payload, str(latest))
    return payload


def _require_schema(payload: dict[str, Any], label: str) -> None:
    if payload.get("schema_version") != _SCHEMA_VERSION:
        raise ValueError(f"{label}: expected schema_version={_SCHEMA_VERSION}")
    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") != _RUNTIME_AUTHORITY:
        raise ValueError(f"{label}: runtime_authority must remain {_RUNTIME_AUTHORITY}")
    if status.get("current_task_id") != "P2-105":
        raise ValueError(f"{label}: current_task_id must be P2-105")
    if status.get("next_task_id") != "P2-106":
        raise ValueError(f"{label}: next_task_id must be P2-106")


def _require_prior_readback(payload: dict[str, Any], label: str) -> None:
    readback = payload.get("prior_readback") or {}
    if readback.get("source_schema_version") != "ai_agent_matched_playbook_learning_gap_v1":
        raise ValueError(f"{label}: prior_readback must chain from P2-104")
    total = readback.get("approval_24h_total")
    matched = readback.get("approval_24h_matched")
    approved_gap = readback.get("approved_without_execution_meta_24h")
    failed = readback.get("execution_failed_with_matched_24h")
    if not all(isinstance(value, int) for value in [total, matched, approved_gap, failed]):
        raise ValueError(f"{label}: prior readback counts must be integers")
    if matched != total:
        raise ValueError(f"{label}: P2-105 requires P2-104 matched_playbook_id gap to be resolved")
    if approved_gap <= 0:
        raise ValueError(f"{label}: approved_without_execution_meta_24h must remain the active P2-105 gap")
    if failed < 1:
        raise ValueError(f"{label}: execution_failed_with_matched_24h must expose at least one failure candidate")
    if readback.get("playbook_updated_24h") != 0:
        raise ValueError(f"{label}: playbook_updated_24h must remain 0 until trust write gate is approved")


def _require_score_truth(payload: dict[str, Any], label: str) -> None:
    truth = payload.get("score_truth") or {}
    required_true = {
        "p2_104_gap_loaded",
        "critic_reviewer_score_required",
        "result_capture_required",
        "playbook_trust_candidate_required",
        "owner_review_required_before_write",
        "post_write_verifier_required",
    }
    missing = sorted(field for field in required_true if truth.get(field) is not True)
    if missing:
        raise ValueError(f"{label}: score truth readiness flags must remain true: {missing}")

    required_false = {
        "runtime_critic_score_enabled",
        "runtime_reviewer_score_enabled",
        "runtime_result_capture_enabled",
        "runtime_learning_write_enabled",
        "playbook_trust_write_enabled",
        "gateway_queue_write_enabled",
        "telegram_send_enabled",
        "production_write_enabled",
        "secret_value_read_enabled",
        "destructive_operation_enabled",
        "work_window_transcript_display_allowed",
    }
    unsafe = sorted(field for field in required_false if truth.get(field) is not False)
    if unsafe:
        raise ValueError(f"{label}: runtime score/write/send flags must remain false: {unsafe}")

    zero_counts = {
        "critic_runtime_score_count_24h",
        "reviewer_runtime_score_count_24h",
        "result_capture_runtime_write_count_24h",
        "learning_write_count_24h",
        "playbook_trust_write_count_24h",
        "gateway_queue_write_count_24h",
        "telegram_send_count_24h",
        "production_write_count_24h",
        "secret_value_read_count_24h",
        "destructive_operation_count_24h",
    }
    non_zero = sorted(field for field in zero_counts if truth.get(field) != 0)
    if non_zero:
        raise ValueError(f"{label}: runtime score/write/send counts must remain zero: {non_zero}")

    if truth.get("approved_without_execution_meta_24h", 0) <= 0:
        raise ValueError(f"{label}: P2-105 must keep approved_without_execution_meta_24h visible")


def _require_scorecards(payload: dict[str, Any], label: str) -> None:
    scorecards = payload.get("agent_scorecards") or []
    scorecard_ids = {scorecard.get("scorecard_id") for scorecard in scorecards}
    required = {
        "scorecard_openclaw_critic_decision_quality",
        "scorecard_openclaw_reviewer_safety_verdict",
        "scorecard_hermes_redaction_operator_report",
        "scorecard_nemotron_failure_candidate_verifier",
        "scorecard_coordinator_disagreement_gate",
    }
    if scorecard_ids != required:
        raise ValueError(f"{label}: scorecards must match {sorted(required)}")

    valid_roles = {"critic", "reviewer", "reporter", "verifier", "coordinator"}
    valid_statuses = {"ready_for_owner_review", "blocked_by_policy"}
    valid_risks = {"low", "medium", "high", "critical"}
    for scorecard in scorecards:
        scorecard_id = scorecard.get("scorecard_id")
        if scorecard.get("role") not in valid_roles:
            raise ValueError(f"{label}: scorecard {scorecard_id} role is invalid")
        if scorecard.get("status") not in valid_statuses:
            raise ValueError(f"{label}: scorecard {scorecard_id} status is invalid")
        if scorecard.get("risk_tier") not in valid_risks:
            raise ValueError(f"{label}: scorecard {scorecard_id} risk_tier is invalid")
        minimum = scorecard.get("minimum_score")
        if not isinstance(minimum, int) or minimum < 0 or minimum > 100:
            raise ValueError(f"{label}: scorecard {scorecard_id} minimum_score must be 0-100")
        if scorecard.get("runtime_score_enabled") is not False:
            raise ValueError(f"{label}: scorecard {scorecard_id} runtime_score_enabled must remain false")
        if not scorecard.get("required_fields") or not scorecard.get("failure_if_missing"):
            raise ValueError(f"{label}: scorecard {scorecard_id} must list required fields and failure text")
        if not _is_redacted_sha256(scorecard.get("evidence_hash")):
            raise ValueError(f"{label}: scorecard {scorecard_id} must expose evidence_hash")


def _require_result_capture_contracts(payload: dict[str, Any], label: str) -> None:
    contracts = payload.get("result_capture_contracts") or []
    contract_ids = {contract.get("contract_id") for contract in contracts}
    required = {
        "capture_approved_execution_result",
        "capture_execution_failed_candidate",
        "capture_pending_human_gate",
        "capture_noop_manual_resolution",
        "capture_post_write_verifier_receipt",
    }
    if contract_ids != required:
        raise ValueError(f"{label}: result capture contracts must match {sorted(required)}")

    valid_statuses = {"ready", "needs_owner_review", "blocked_by_policy"}
    valid_risks = {"low", "medium", "high", "critical"}
    for contract in contracts:
        contract_id = contract.get("contract_id")
        if contract.get("status") not in valid_statuses:
            raise ValueError(f"{label}: contract {contract_id} status is invalid")
        if contract.get("risk_tier") not in valid_risks:
            raise ValueError(f"{label}: contract {contract_id} risk_tier is invalid")
        if contract.get("write_enabled") is not False:
            raise ValueError(f"{label}: contract {contract_id} write_enabled must remain false")
        if contract.get("runtime_writer_enabled") is not False:
            raise ValueError(f"{label}: contract {contract_id} runtime_writer_enabled must remain false")
        if not contract.get("required_fields") or not contract.get("blocker_summary"):
            raise ValueError(f"{label}: contract {contract_id} must list required fields and blocker summary")
        if not _is_redacted_sha256(contract.get("evidence_hash")):
            raise ValueError(f"{label}: contract {contract_id} must expose evidence_hash")


def _require_promotion_gates(payload: dict[str, Any], label: str) -> None:
    gates = payload.get("promotion_gates") or []
    gate_ids = {gate.get("gate_id") for gate in gates}
    required = {
        "gate_minimum_critic_reviewer_scores",
        "gate_disagreement_human_hold",
        "gate_result_capture_payload_complete",
        "gate_redaction_no_private_context",
        "gate_post_write_verifier",
        "gate_telegram_operator_digest",
    }
    if gate_ids != required:
        raise ValueError(f"{label}: promotion gates must match {sorted(required)}")
    for gate in gates:
        gate_id = gate.get("gate_id")
        if gate.get("status") not in {"ready", "needs_owner_review", "blocked_by_policy"}:
            raise ValueError(f"{label}: gate {gate_id} status is invalid")
        if gate.get("creates_runtime_write") is not False:
            raise ValueError(f"{label}: gate {gate_id} creates_runtime_write must remain false")
        if not gate.get("required_before") or not gate.get("failure_if_missing"):
            raise ValueError(f"{label}: gate {gate_id} must list required_before and failure_if_missing")


def _require_candidate_routes(payload: dict[str, Any], label: str) -> None:
    routes = payload.get("candidate_routes") or []
    route_ids = {route.get("route_id") for route in routes}
    required = {
        "route_approved_to_result_capture",
        "route_failed_to_negative_learning_candidate",
        "route_pending_to_human_gate",
        "route_score_ready_to_playbook_trust_hold",
    }
    if route_ids != required:
        raise ValueError(f"{label}: candidate routes must match {sorted(required)}")
    for route in routes:
        route_id = route.get("route_id")
        if route.get("status") not in {"ready_for_owner_review", "blocked_by_policy"}:
            raise ValueError(f"{label}: route {route_id} status is invalid")
        if route.get("write_enabled") is not False:
            raise ValueError(f"{label}: route {route_id} write_enabled must remain false")
        if not route.get("next_gate"):
            raise ValueError(f"{label}: route {route_id} must list next_gate")
        if not _is_redacted_sha256(route.get("evidence_hash")):
            raise ValueError(f"{label}: route {route_id} must expose evidence_hash")


def _require_redaction_contract(payload: dict[str, Any], label: str) -> None:
    contract = payload.get("display_redaction_contract") or {}
    required_false = {
        "raw_prompt_display_allowed",
        "private_reasoning_display_allowed",
        "secret_value_display_allowed",
        "raw_telegram_payload_display_allowed",
        "work_window_transcript_display_allowed",
    }
    if contract.get("redaction_required") is not True:
        raise ValueError(f"{label}: display redaction must remain required")
    unsafe = sorted(field for field in required_false if contract.get(field) is not False)
    if unsafe:
        raise ValueError(f"{label}: display redaction fields must remain false: {unsafe}")


def _require_no_forbidden_display_terms(payload: dict[str, Any], label: str) -> None:
    forbidden_terms = {
        "工作視窗",
        "對話內容",
        "批准！繼續",
        "In app browser",
        "My request for Codex",
        "browser_context",
        "codex_user_message",
        "prompt_text",
        "raw prompt",
        "private reasoning",
        "chain of thought",
        "private_reasoning",
        "chain_of_thought",
        "authorization_header",
        "work window transcript",
        "internal collaboration transcript",
    }

    hits: list[str] = []

    def walk(value: Any, path: str) -> None:
        if isinstance(value, dict):
            for key, nested in value.items():
                walk(nested, f"{path}.{key}" if path else str(key))
            return
        if isinstance(value, list):
            for index, nested in enumerate(value):
                walk(nested, f"{path}[{index}]")
            return
        if isinstance(value, str):
            matched = sorted(term for term in forbidden_terms if term in value)
            if matched:
                hits.append(f"{path}: {', '.join(matched)}")

    walk(payload, "")
    if hits:
        raise ValueError(f"{label}: forbidden display terms found: {hits}")


def _require_rollup_consistency(payload: dict[str, Any], label: str) -> None:
    rollups = payload.get("rollups") or {}
    truth = payload.get("score_truth") or {}
    readback = payload.get("prior_readback") or {}
    scorecards = payload.get("agent_scorecards") or []
    contracts = payload.get("result_capture_contracts") or []
    gates = payload.get("promotion_gates") or []
    routes = payload.get("candidate_routes") or []

    expected = {
        "scorecard_count": len(scorecards),
        "result_capture_contract_count": len(contracts),
        "promotion_gate_count": len(gates),
        "candidate_route_count": len(routes),
        "approval_24h_total": readback.get("approval_24h_total"),
        "approved_without_execution_meta_24h": readback.get("approved_without_execution_meta_24h"),
        "execution_failed_with_matched_24h": readback.get("execution_failed_with_matched_24h"),
        "pending_with_matched_24h": readback.get("pending_with_matched_24h"),
        "blocked_gate_count": sum(1 for gate in gates if gate.get("status") == "blocked_by_policy"),
        "owner_review_gate_count": sum(1 for gate in gates if gate.get("status") == "needs_owner_review"),
        "runtime_critic_score_count": truth.get("critic_runtime_score_count_24h"),
        "runtime_reviewer_score_count": truth.get("reviewer_runtime_score_count_24h"),
        "result_capture_runtime_write_count": truth.get("result_capture_runtime_write_count_24h"),
        "learning_write_count": truth.get("learning_write_count_24h"),
        "playbook_trust_write_count": truth.get("playbook_trust_write_count_24h"),
        "gateway_queue_write_count": truth.get("gateway_queue_write_count_24h"),
        "telegram_send_count": truth.get("telegram_send_count_24h"),
        "production_write_count": truth.get("production_write_count_24h"),
        "secret_value_read_count": truth.get("secret_value_read_count_24h"),
        "destructive_operation_count": truth.get("destructive_operation_count_24h"),
    }
    mismatches = {
        key: {"expected": expected_value, "actual": rollups.get(key)}
        for key, expected_value in expected.items()
        if rollups.get(key) != expected_value
    }
    if mismatches:
        raise ValueError(f"{label}: rollup counts mismatch: {mismatches}")


def _is_redacted_sha256(value: Any) -> bool:
    if not isinstance(value, str):
        return False
    if not value.startswith("sha256:") or len(value) != 71:
        return False
    return all(char in "0123456789abcdef" for char in value.removeprefix("sha256:"))
