import copy
import json

import pytest

from src.services.ai_agent_critic_reviewer_result_capture import (
    load_latest_ai_agent_critic_reviewer_result_capture,
)


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


def test_load_latest_ai_agent_critic_reviewer_result_capture():
    data = load_latest_ai_agent_critic_reviewer_result_capture()

    assert data["schema_version"] == "ai_agent_critic_reviewer_result_capture_v1"
    assert data["program_status"]["current_task_id"] == "P2-105"
    assert data["program_status"]["next_task_id"] == "P2-106"
    assert data["program_status"]["overall_completion_percent"] == 100
    assert data["prior_readback"]["approval_24h_total"] == 66
    assert data["prior_readback"]["approval_24h_matched"] == 66
    assert data["prior_readback"]["approved_without_execution_meta_24h"] == 63
    assert data["score_truth"]["critic_reviewer_score_required"] is True
    assert data["score_truth"]["result_capture_required"] is True
    assert data["score_truth"]["runtime_critic_score_enabled"] is False
    assert data["score_truth"]["runtime_reviewer_score_enabled"] is False
    assert data["score_truth"]["telegram_send_enabled"] is False
    assert data["rollups"]["scorecard_count"] == 5
    assert data["rollups"]["result_capture_contract_count"] == 5
    assert data["rollups"]["promotion_gate_count"] == 6
    assert data["rollups"]["candidate_route_count"] == 4
    assert data["rollups"]["runtime_critic_score_count"] == 0
    assert data["rollups"]["runtime_reviewer_score_count"] == 0
    assert data["rollups"]["result_capture_runtime_write_count"] == 0
    assert data["rollups"]["learning_write_count"] == 0
    assert data["rollups"]["playbook_trust_write_count"] == 0
    assert data["rollups"]["telegram_send_count"] == 0


def test_rejects_unresolved_p2_104_matched_gap(tmp_path):
    data = load_latest_ai_agent_critic_reviewer_result_capture()
    bad = copy.deepcopy(data)
    bad["prior_readback"]["approval_24h_matched"] = 65
    _write_snapshot(tmp_path, bad)

    with pytest.raises(ValueError, match="matched_playbook_id"):
        load_latest_ai_agent_critic_reviewer_result_capture(tmp_path)


def test_rejects_runtime_critic_score_enabled(tmp_path):
    data = load_latest_ai_agent_critic_reviewer_result_capture()
    bad = copy.deepcopy(data)
    bad["score_truth"]["runtime_critic_score_enabled"] = True
    _write_snapshot(tmp_path, bad)

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


def test_rejects_runtime_score_count(tmp_path):
    data = load_latest_ai_agent_critic_reviewer_result_capture()
    bad = copy.deepcopy(data)
    bad["score_truth"]["critic_runtime_score_count_24h"] = 1
    bad["rollups"]["runtime_critic_score_count"] = 1
    _write_snapshot(tmp_path, bad)

    with pytest.raises(ValueError, match="runtime score/write/send counts"):
        load_latest_ai_agent_critic_reviewer_result_capture(tmp_path)


def test_rejects_scorecard_runtime_score(tmp_path):
    data = load_latest_ai_agent_critic_reviewer_result_capture()
    bad = copy.deepcopy(data)
    bad["agent_scorecards"][0]["runtime_score_enabled"] = True
    _write_snapshot(tmp_path, bad)

    with pytest.raises(ValueError, match="runtime_score_enabled"):
        load_latest_ai_agent_critic_reviewer_result_capture(tmp_path)


def test_rejects_result_capture_write_enabled(tmp_path):
    data = load_latest_ai_agent_critic_reviewer_result_capture()
    bad = copy.deepcopy(data)
    bad["result_capture_contracts"][0]["write_enabled"] = True
    _write_snapshot(tmp_path, bad)

    with pytest.raises(ValueError, match="write_enabled"):
        load_latest_ai_agent_critic_reviewer_result_capture(tmp_path)


def test_rejects_promotion_gate_runtime_write(tmp_path):
    data = load_latest_ai_agent_critic_reviewer_result_capture()
    bad = copy.deepcopy(data)
    bad["promotion_gates"][0]["creates_runtime_write"] = True
    _write_snapshot(tmp_path, bad)

    with pytest.raises(ValueError, match="creates_runtime_write"):
        load_latest_ai_agent_critic_reviewer_result_capture(tmp_path)


def test_rejects_candidate_route_write(tmp_path):
    data = load_latest_ai_agent_critic_reviewer_result_capture()
    bad = copy.deepcopy(data)
    bad["candidate_routes"][0]["write_enabled"] = True
    _write_snapshot(tmp_path, bad)

    with pytest.raises(ValueError, match="write_enabled"):
        load_latest_ai_agent_critic_reviewer_result_capture(tmp_path)


def test_rejects_forbidden_display_terms(tmp_path):
    data = load_latest_ai_agent_critic_reviewer_result_capture()
    bad = copy.deepcopy(data)
    bad["agent_scorecards"][0]["failure_if_missing"] = "不得顯示工作視窗對話內容"
    _write_snapshot(tmp_path, bad)

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


def test_rejects_forbidden_private_reasoning_terms(tmp_path):
    data = load_latest_ai_agent_critic_reviewer_result_capture()
    bad = copy.deepcopy(data)
    bad["display_redaction_contract"]["blocked_display_fields"] = [
        "raw prompt",
        "private reasoning",
        "chain of thought",
    ]
    _write_snapshot(tmp_path, bad)

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


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

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