from __future__ import annotations

import copy
import json
from pathlib import Path

import pytest

from src.services.ai_agent_result_capture_release_decision_owner_response_acceptance_gate import (
    load_latest_ai_agent_result_capture_release_decision_owner_response_acceptance_gate,
)


def test_load_latest_release_decision_owner_response_acceptance_gate_snapshot() -> None:
    snapshot = load_latest_ai_agent_result_capture_release_decision_owner_response_acceptance_gate()

    assert snapshot["schema_version"] == "ai_agent_result_capture_release_decision_owner_response_acceptance_gate_v1"
    assert snapshot["program_status"]["current_task_id"] == "P2-145"
    assert snapshot["program_status"]["next_task_id"] == "P2-146"
    assert snapshot["program_status"]["overall_completion_percent"] == 100
    assert snapshot["program_status"]["runtime_authority"] == (
        "result_capture_release_decision_owner_response_acceptance_gate_only_no_live_write"
    )

    rollups = snapshot["rollups"]
    assert rollups["acceptance_gate_lane_count"] == 5
    assert rollups["required_owner_field_count"] == 18
    assert rollups["acceptance_validation_check_count"] == 6
    assert rollups["acceptance_rejection_guard_count"] == 6
    assert rollups["operator_action_count"] == 5
    assert rollups["blocked_no_external_response_count"] == 5
    assert rollups["acceptance_ready_count"] == 0
    assert rollups["no_acceptable_external_response_count"] == 5
    assert rollups["owner_response_received_count"] == 0
    assert rollups["owner_response_accepted_count"] == 0
    assert rollups["owner_response_rejected_count"] == 0
    assert rollups["redacted_payload_ingested_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["production_write_count"] == 0


def test_owner_response_acceptance_gate_keeps_all_runtime_gates_closed() -> None:
    snapshot = load_latest_ai_agent_result_capture_release_decision_owner_response_acceptance_gate()
    truth = snapshot["owner_response_acceptance_truth"]

    assert truth["p2_144_readback_loaded"] is True
    assert truth["p2_143_preflight_baseline_preserved"] is True
    assert truth["owner_response_acceptance_gate_ready"] is True
    assert truth["acceptance_gate_only_mode"] is True
    assert truth["no_acceptable_external_response"] is True
    assert truth["requires_redacted_payload"] is True
    assert truth["owner_response_received"] is False
    assert truth["owner_response_accepted"] is False
    assert truth["redacted_payload_ingested"] is False
    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_acceptance_gate_lane(tmp_path: Path) -> None:
    snapshot = copy.deepcopy(load_latest_ai_agent_result_capture_release_decision_owner_response_acceptance_gate())
    snapshot["acceptance_gate_lanes"] = snapshot["acceptance_gate_lanes"][:-1]
    snapshot["rollups"]["acceptance_gate_lane_count"] = 4
    snapshot["rollups"]["blocked_no_external_response_count"] = 4
    snapshot["rollups"]["no_acceptable_external_response_count"] = 4
    _write_snapshot(tmp_path, snapshot)

    with pytest.raises(ValueError, match="acceptance gate lanes ids mismatch"):
        load_latest_ai_agent_result_capture_release_decision_owner_response_acceptance_gate(tmp_path)


def test_rejects_owner_response_accepted_drift(tmp_path: Path) -> None:
    snapshot = copy.deepcopy(load_latest_ai_agent_result_capture_release_decision_owner_response_acceptance_gate())
    snapshot["owner_response_acceptance_truth"]["owner_response_accepted"] = True
    _write_snapshot(tmp_path, snapshot)

    with pytest.raises(ValueError, match="flags must remain false"):
        load_latest_ai_agent_result_capture_release_decision_owner_response_acceptance_gate(tmp_path)


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


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


def test_rejects_chinese_forbidden_display_terms(tmp_path: Path) -> None:
    snapshot = copy.deepcopy(load_latest_ai_agent_result_capture_release_decision_owner_response_acceptance_gate())
    snapshot["operator_actions"][0]["operator_instruction"] = "不要顯示工作視窗內容"
    _write_snapshot(tmp_path, snapshot)

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


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