import copy
import json

import pytest

from src.services.ai_agent_runtime_readback_approval_package import (
    load_latest_ai_agent_runtime_readback_approval_package,
)


def _write_snapshot(tmp_path, payload):
    path = tmp_path / "ai_agent_runtime_readback_approval_package_2026-06-13.json"
    path.write_text(json.dumps(payload), encoding="utf-8")
    return path


def test_load_latest_ai_agent_runtime_readback_approval_package():
    data = load_latest_ai_agent_runtime_readback_approval_package()

    assert data["schema_version"] == "ai_agent_runtime_readback_approval_package_v1"
    assert data["program_status"]["current_task_id"] == "P2-109"
    assert data["program_status"]["next_task_id"] == "P2-110"
    assert data["program_status"]["overall_completion_percent"] == 100
    assert data["prior_readback_readiness"]["source_schema_version"] == (
        "ai_agent_owner_approved_result_capture_readback_v1"
    )
    assert data["prior_readback_readiness"]["readback_digest_count"] == 5
    assert data["prior_readback_readiness"]["blocked_total_count"] == 7
    assert data["approval_package_truth"]["p2_107_readback_loaded"] is True
    assert data["approval_package_truth"]["approval_package_ready"] is True
    assert data["approval_package_truth"]["canonical_readback_plan_ready"] is True
    assert data["approval_package_truth"]["rollback_drill_ready"] is True
    assert data["approval_package_truth"]["telegram_failure_receipt_gate_ready"] is True
    assert data["approval_package_truth"]["canonical_runtime_readback_enabled"] is False
    assert data["approval_package_truth"]["telegram_failure_receipt_send_enabled"] is False
    assert data["approval_package_truth"]["bot_api_call_enabled"] is False
    assert data["approval_package_truth"]["rollback_work_item_write_enabled"] is False
    assert data["approval_package_truth"]["runtime_readback_execution_count"] == 0
    assert data["approval_package_truth"]["telegram_failure_receipt_send_count_24h"] == 0
    assert data["rollups"]["approval_packet_count"] == 5
    assert data["rollups"]["canonical_readback_plan_count"] == 4
    assert data["rollups"]["rollback_drill_lane_count"] == 4
    assert data["rollups"]["telegram_failure_receipt_gate_count"] == 4
    assert data["rollups"]["operator_action_count"] == 5
    assert data["rollups"]["approval_required_packet_count"] == 3
    assert data["rollups"]["blocked_packet_count"] == 1
    assert data["rollups"]["blocked_readback_plan_count"] == 1
    assert data["rollups"]["blocked_rollback_lane_count"] == 2
    assert data["rollups"]["blocked_telegram_gate_count"] == 1
    assert data["rollups"]["owner_approval_received_count"] == 0
    assert data["rollups"]["runtime_readback_execution_count"] == 0
    assert data["rollups"]["result_capture_write_count"] == 0
    assert data["rollups"]["score_write_count"] == 0
    assert data["rollups"]["learning_write_count"] == 0
    assert data["rollups"]["playbook_trust_write_count"] == 0
    assert data["rollups"]["reviewer_queue_write_count"] == 0
    assert data["rollups"]["gateway_queue_write_count"] == 0
    assert data["rollups"]["telegram_failure_receipt_send_count"] == 0
    assert data["rollups"]["bot_api_call_count"] == 0
    assert data["rollups"]["rollback_work_item_write_count"] == 0
    assert data["rollups"]["production_write_count"] == 0


def test_rejects_runtime_readback_enabled(tmp_path):
    data = load_latest_ai_agent_runtime_readback_approval_package()
    bad = copy.deepcopy(data)
    bad["approval_package_truth"]["canonical_runtime_readback_enabled"] = True
    _write_snapshot(tmp_path, bad)

    with pytest.raises(ValueError, match="runtime read/write/send flags"):
        load_latest_ai_agent_runtime_readback_approval_package(tmp_path)


def test_rejects_runtime_execution_count(tmp_path):
    data = load_latest_ai_agent_runtime_readback_approval_package()
    bad = copy.deepcopy(data)
    bad["approval_package_truth"]["runtime_readback_execution_count"] = 1
    bad["rollups"]["runtime_readback_execution_count"] = 1
    _write_snapshot(tmp_path, bad)

    with pytest.raises(ValueError, match="live counters"):
        load_latest_ai_agent_runtime_readback_approval_package(tmp_path)


def test_rejects_packet_runtime_write(tmp_path):
    data = load_latest_ai_agent_runtime_readback_approval_package()
    bad = copy.deepcopy(data)
    bad["approval_packet_templates"][0]["runtime_write_allowed"] = True
    _write_snapshot(tmp_path, bad)

    with pytest.raises(ValueError, match="runtime_write_allowed"):
        load_latest_ai_agent_runtime_readback_approval_package(tmp_path)


def test_rejects_canonical_live_query(tmp_path):
    data = load_latest_ai_agent_runtime_readback_approval_package()
    bad = copy.deepcopy(data)
    bad["canonical_readback_plans"][0]["live_query_enabled"] = True
    _write_snapshot(tmp_path, bad)

    with pytest.raises(ValueError, match="live_query_enabled"):
        load_latest_ai_agent_runtime_readback_approval_package(tmp_path)


def test_rejects_telegram_send_enabled(tmp_path):
    data = load_latest_ai_agent_runtime_readback_approval_package()
    bad = copy.deepcopy(data)
    bad["telegram_failure_receipt_gates"][0]["telegram_send_enabled"] = True
    _write_snapshot(tmp_path, bad)

    with pytest.raises(ValueError, match="telegram_send_enabled"):
        load_latest_ai_agent_runtime_readback_approval_package(tmp_path)


def test_rejects_forbidden_display_terms(tmp_path):
    data = load_latest_ai_agent_runtime_readback_approval_package()
    bad = copy.deepcopy(data)
    bad["operator_actions"][0]["operator_instruction"] = "不得顯示工作視窗內容"
    _write_snapshot(tmp_path, bad)

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


def test_rejects_rollup_mismatch(tmp_path):
    data = load_latest_ai_agent_runtime_readback_approval_package()
    bad = copy.deepcopy(data)
    bad["rollups"]["approval_packet_count"] = 999
    _write_snapshot(tmp_path, bad)

    with pytest.raises(ValueError, match="rollup counts"):
        load_latest_ai_agent_runtime_readback_approval_package(tmp_path)
