from __future__ import annotations

import copy
import json
from pathlib import Path

import pytest

from src.services.ai_agent_result_capture_release_decision_hold import (
    load_latest_ai_agent_result_capture_release_decision_hold,
)


def test_load_latest_release_decision_hold_snapshot() -> None:
    snapshot = load_latest_ai_agent_result_capture_release_decision_hold()

    assert snapshot["schema_version"] == "ai_agent_result_capture_release_decision_hold_v1"
    assert snapshot["program_status"]["current_task_id"] == "P2-138"
    assert snapshot["program_status"]["next_task_id"] == "P2-139"
    assert snapshot["program_status"]["overall_completion_percent"] == 100
    assert snapshot["program_status"]["runtime_authority"] == "result_capture_release_decision_hold_only_no_live_write"

    rollups = snapshot["rollups"]
    assert rollups["release_decision_hold_count"] == 5
    assert rollups["owner_decision_hold_count"] == 5
    assert rollups["verifier_decision_hold_count"] == 5
    assert rollups["rollback_decision_hold_count"] == 5
    assert rollups["maintenance_window_decision_hold_count"] == 5
    assert rollups["live_apply_decision_hold_count"] == 5
    assert rollups["blocked_decision_transition_count"] == 6
    assert rollups["operator_action_count"] == 5
    assert (
        rollups["approval_required_release_decision_count"]
        + rollups["approval_required_owner_decision_count"]
        + rollups["approval_required_verifier_decision_count"]
        + rollups["approval_required_rollback_decision_count"]
        + rollups["approval_required_maintenance_window_decision_count"]
        + rollups["approval_required_live_apply_decision_count"]
    ) == 12
    assert (
        rollups["blocked_release_decision_count"]
        + rollups["blocked_owner_decision_count"]
        + rollups["blocked_verifier_decision_count"]
        + rollups["blocked_rollback_decision_count"]
        + rollups["blocked_maintenance_window_decision_count"]
        + rollups["blocked_live_apply_decision_count"]
        + rollups["critical_blocker_count"]
    ) == 12

    assert rollups["owner_release_authorized_count"] == 0
    assert rollups["owner_review_approved_count"] == 0
    assert rollups["owner_decision_approved_count"] == 0
    assert rollups["verifier_decision_approved_count"] == 0
    assert rollups["maintenance_window_approved_count"] == 0
    assert rollups["release_decision_pass_count"] == 0
    assert rollups["release_authorization_granted_count"] == 0
    assert rollups["release_authorization_pass_count"] == 0
    assert rollups["rollback_release_pass_count"] == 0
    assert rollups["live_apply_release_pass_count"] == 0
    assert rollups["writer_apply_count"] == 0
    assert rollups["reviewer_queue_write_count"] == 0
    assert rollups["gateway_queue_write_count"] == 0
    assert rollups["telegram_send_count"] == 0
    assert rollups["bot_api_call_count"] == 0
    assert rollups["result_capture_write_count"] == 0
    assert rollups["learning_write_count"] == 0
    assert rollups["playbook_trust_write_count"] == 0
    assert rollups["production_write_count"] == 0


def test_release_decision_hold_truth_keeps_all_live_paths_closed() -> None:
    snapshot = load_latest_ai_agent_result_capture_release_decision_hold()
    truth = snapshot["release_decision_hold_truth"]

    assert truth["p2_137_owner_review_packet_loaded"] is True
    assert truth["release_decision_hold_ready"] is True
    assert truth["owner_decision_required"] is True
    assert truth["maintenance_window_decision_required"] is True
    assert truth["owner_release_authorized"] is False
    assert truth["owner_review_approved"] is False
    assert truth["owner_decision_approved"] is False
    assert truth["verifier_decision_approved"] is False
    assert truth["release_decision_passed"] is False
    assert truth["release_authorization_granted"] is False
    assert truth["release_authorization_passed"] is False
    assert truth["rollback_release_passed"] is False
    assert truth["live_apply_release_passed"] is False
    assert truth["reviewer_queue_write_enabled"] is False
    assert truth["gateway_queue_write_enabled"] is False
    assert truth["telegram_send_enabled"] is False
    assert truth["production_write_enabled"] is False
    assert truth["secret_read_enabled"] is False
    assert truth["destructive_operation_enabled"] is False


def test_rejects_release_decision_passed(tmp_path: Path) -> None:
    snapshot = copy.deepcopy(load_latest_ai_agent_result_capture_release_decision_hold())
    snapshot["release_decision_holds"][0]["release_decision_passed"] = True
    _write_snapshot(tmp_path, snapshot)

    with pytest.raises(ValueError, match="must stay unapproved, ungranted, and unpassed"):
        load_latest_ai_agent_result_capture_release_decision_hold(tmp_path)


def test_rejects_owner_decision_approved(tmp_path: Path) -> None:
    snapshot = copy.deepcopy(load_latest_ai_agent_result_capture_release_decision_hold())
    snapshot["owner_decision_holds"][0]["owner_decision_approved"] = True
    _write_snapshot(tmp_path, snapshot)

    with pytest.raises(ValueError, match="must stay unauthorized and unapproved"):
        load_latest_ai_agent_result_capture_release_decision_hold(tmp_path)


def test_rejects_maintenance_window_approved(tmp_path: Path) -> None:
    snapshot = copy.deepcopy(load_latest_ai_agent_result_capture_release_decision_hold())
    snapshot["maintenance_window_decision_holds"][0]["maintenance_window_approved"] = True
    _write_snapshot(tmp_path, snapshot)

    with pytest.raises(ValueError, match="must stay unapproved and unpassed"):
        load_latest_ai_agent_result_capture_release_decision_hold(tmp_path)


def test_rejects_queue_write_drift(tmp_path: Path) -> None:
    snapshot = copy.deepcopy(load_latest_ai_agent_result_capture_release_decision_hold())
    snapshot["rollups"]["gateway_queue_write_count"] = 1
    _write_snapshot(tmp_path, snapshot)

    with pytest.raises(ValueError, match="rollups mismatch"):
        load_latest_ai_agent_result_capture_release_decision_hold(tmp_path)


def test_rejects_forbidden_display_terms(tmp_path: Path) -> None:
    snapshot = copy.deepcopy(load_latest_ai_agent_result_capture_release_decision_hold())
    snapshot["operator_actions"][0]["operator_instruction"] = "不要顯示 raw_prompt"
    _write_snapshot(tmp_path, snapshot)

    with pytest.raises(ValueError, match="forbidden display terms leaked"):
        load_latest_ai_agent_result_capture_release_decision_hold(tmp_path)


def _write_snapshot(directory: Path, payload: dict) -> None:
    path = directory / "ai_agent_result_capture_release_decision_hold_2099-01-01.json"
    path.write_text(json.dumps(payload, ensure_ascii=False), encoding="utf-8")
