from __future__ import annotations

import copy
import json
from pathlib import Path

import pytest

from src.services.ai_agent_result_capture_release_decision_next_handoff import (
    load_latest_ai_agent_result_capture_release_decision_next_handoff,
)


def test_load_latest_release_decision_next_handoff_snapshot() -> None:
    snapshot = load_latest_ai_agent_result_capture_release_decision_next_handoff()

    assert snapshot["schema_version"] == "ai_agent_result_capture_release_decision_next_handoff_v1"
    assert snapshot["program_status"]["current_task_id"] == "P2-140"
    assert snapshot["program_status"]["next_task_id"] == "P2-141"
    assert snapshot["program_status"]["overall_completion_percent"] == 100
    assert snapshot["program_status"]["runtime_authority"] == "result_capture_release_decision_next_handoff_only_no_live_write"

    rollups = snapshot["rollups"]
    assert rollups["next_gate_handoff_count"] == 5
    assert rollups["stale_operator_action_count"] == 1
    assert rollups["blocked_handoff_transition_count"] == 6
    assert rollups["operator_action_count"] == 5
    assert rollups["approval_required_subtotal"] == 12
    assert rollups["blocked_and_critical_subtotal"] == 12
    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_next_handoff_truth_contains_stale_self_loop_without_writes() -> None:
    snapshot = load_latest_ai_agent_result_capture_release_decision_next_handoff()
    truth = snapshot["next_handoff_truth"]

    assert truth["p2_139_release_decision_readback_loaded"] is True
    assert truth["next_task_id_alignment_checked"] is True
    assert truth["stale_self_loop_detected"] is True
    assert truth["stale_self_loop_contained"] is True
    assert truth["p2_140_next_handoff_only"] is True
    assert truth["operator_instruction_requires_p2_141"] is True
    assert truth["release_authorization_granted"] 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_missing_stale_self_loop_containment(tmp_path: Path) -> None:
    snapshot = copy.deepcopy(load_latest_ai_agent_result_capture_release_decision_next_handoff())
    snapshot["stale_operator_action_containments"] = []
    snapshot["rollups"]["stale_operator_action_count"] = 0
    _write_snapshot(tmp_path, snapshot)

    with pytest.raises(ValueError, match="expected 1 stale operator action containments"):
        load_latest_ai_agent_result_capture_release_decision_next_handoff(tmp_path)


def test_rejects_operator_action_that_points_back_to_p2_139(tmp_path: Path) -> None:
    snapshot = copy.deepcopy(load_latest_ai_agent_result_capture_release_decision_next_handoff())
    snapshot["operator_actions"][0]["action_id"] = "prepare_p2_139_release_decision_readback"
    _write_snapshot(tmp_path, snapshot)

    with pytest.raises(ValueError, match="must not point back to P2-139"):
        load_latest_ai_agent_result_capture_release_decision_next_handoff(tmp_path)


def test_rejects_gateway_write_drift(tmp_path: Path) -> None:
    snapshot = copy.deepcopy(load_latest_ai_agent_result_capture_release_decision_next_handoff())
    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_next_handoff(tmp_path)


def test_rejects_forbidden_display_terms(tmp_path: Path) -> None:
    snapshot = copy.deepcopy(load_latest_ai_agent_result_capture_release_decision_next_handoff())
    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_next_handoff(tmp_path)


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