import copy
import json

import pytest

from src.services.ai_agent_runtime_readback_implementation_review import (
    load_latest_ai_agent_runtime_readback_implementation_review,
)


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


def test_load_latest_ai_agent_runtime_readback_implementation_review():
    data = load_latest_ai_agent_runtime_readback_implementation_review()

    assert data["schema_version"] == "ai_agent_runtime_readback_implementation_review_v1"
    assert data["program_status"]["current_task_id"] == "P2-110"
    assert data["program_status"]["next_task_id"] == "P2-111"
    assert data["program_status"]["overall_completion_percent"] == 100
    assert data["prior_approval_package"]["source_schema_version"] == "ai_agent_runtime_readback_approval_package_v1"
    assert data["prior_approval_package"]["approval_packet_count"] == 5
    assert data["prior_approval_package"]["blocked_total_count"] == 5
    assert data["implementation_review_truth"]["p2_109_approval_package_loaded"] is True
    assert data["implementation_review_truth"]["implementation_review_ready"] is True
    assert data["implementation_review_truth"]["adapter_contract_ready"] is True
    assert data["implementation_review_truth"]["verifier_contract_ready"] is True
    assert data["implementation_review_truth"]["redaction_contract_ready"] is True
    assert data["implementation_review_truth"]["telemetry_receipt_contract_ready"] is True
    assert data["implementation_review_truth"]["canonical_runtime_readback_enabled"] is False
    assert data["implementation_review_truth"]["live_query_enabled"] is False
    assert data["implementation_review_truth"]["runtime_result_capture_write_enabled"] is False
    assert data["implementation_review_truth"]["telegram_failure_receipt_send_enabled"] is False
    assert data["implementation_review_truth"]["bot_api_call_enabled"] is False
    assert data["implementation_review_truth"]["rollback_work_item_write_enabled"] is False
    assert data["implementation_review_truth"]["runtime_readback_execution_count"] == 0
    assert data["implementation_review_truth"]["live_query_count_24h"] == 0
    assert data["rollups"]["implementation_review_card_count"] == 5
    assert data["rollups"]["no_write_verifier_check_count"] == 5
    assert data["rollups"]["implementation_blocker_count"] == 5
    assert data["rollups"]["operator_action_count"] == 5
    assert data["rollups"]["approval_required_card_count"] == 2
    assert data["rollups"]["blocked_card_count"] == 1
    assert data["rollups"]["blocked_verifier_check_count"] == 1
    assert data["rollups"]["critical_blocker_count"] == 2
    assert data["rollups"]["owner_approval_received_count"] == 0
    assert data["rollups"]["runtime_readback_execution_count"] == 0
    assert data["rollups"]["live_query_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_live_query_enabled(tmp_path):
    data = load_latest_ai_agent_runtime_readback_implementation_review()
    bad = copy.deepcopy(data)
    bad["implementation_review_truth"]["live_query_enabled"] = True
    _write_snapshot(tmp_path, bad)

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


def test_rejects_runtime_execution_count(tmp_path):
    data = load_latest_ai_agent_runtime_readback_implementation_review()
    bad = copy.deepcopy(data)
    bad["implementation_review_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_implementation_review(tmp_path)


def test_rejects_card_write_mode(tmp_path):
    data = load_latest_ai_agent_runtime_readback_implementation_review()
    bad = copy.deepcopy(data)
    bad["implementation_review_cards"][0]["no_write_mode"] = False
    _write_snapshot(tmp_path, bad)

    with pytest.raises(ValueError, match="no_write_mode"):
        load_latest_ai_agent_runtime_readback_implementation_review(tmp_path)


def test_rejects_verifier_live_query(tmp_path):
    data = load_latest_ai_agent_runtime_readback_implementation_review()
    bad = copy.deepcopy(data)
    bad["no_write_verifier_checks"][0]["live_query_enabled"] = True
    _write_snapshot(tmp_path, bad)

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


def test_rejects_missing_blocker_resolution(tmp_path):
    data = load_latest_ai_agent_runtime_readback_implementation_review()
    bad = copy.deepcopy(data)
    bad["implementation_blockers"][0]["required_resolution"] = ""
    _write_snapshot(tmp_path, bad)

    with pytest.raises(ValueError, match="blocked action and resolution"):
        load_latest_ai_agent_runtime_readback_implementation_review(tmp_path)


def test_rejects_forbidden_display_terms(tmp_path):
    data = load_latest_ai_agent_runtime_readback_implementation_review()
    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_implementation_review(tmp_path)


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

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