import copy
import json

import pytest

from src.services.ai_agent_matched_playbook_learning_gap import (
    load_latest_ai_agent_matched_playbook_learning_gap,
)


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


def test_load_latest_ai_agent_matched_playbook_learning_gap():
    data = load_latest_ai_agent_matched_playbook_learning_gap()

    assert data["schema_version"] == "ai_agent_matched_playbook_learning_gap_v1"
    assert data["program_status"]["current_task_id"] == "P2-104"
    assert data["program_status"]["next_task_id"] == "P2-105"
    assert data["program_status"]["overall_completion_percent"] == 100
    assert data["production_readback"]["rls_fail_closed_verified"] is True
    assert data["production_readback"]["approval_24h_total"] == 66
    assert data["production_readback"]["approval_24h_matched"] == 66
    assert data["production_readback"]["matched_rate_24h_percent"] == 100
    assert data["production_readback"]["playbook_updated_24h"] == 0
    assert data["learning_gap_truth"]["matched_playbook_id_gap_resolved"] is True
    assert data["learning_gap_truth"]["execution_learning_gap_detected"] is True
    assert data["learning_gap_truth"]["approved_without_execution_meta_24h"] == 63
    assert data["learning_gap_truth"]["playbook_trust_write_enabled"] is False
    assert data["learning_gap_truth"]["telegram_send_enabled"] is False
    assert data["rollups"]["gap_lane_count"] == 5
    assert data["rollups"]["passed_lane_count"] == 1
    assert data["rollups"]["blocked_lane_count"] == 2
    assert data["rollups"]["owner_review_lane_count"] == 2
    assert data["rollups"]["learning_gate_count"] == 5
    assert data["rollups"]["writeback_candidate_count"] == 4
    assert data["rollups"]["live_learning_write_count"] == 0
    assert data["rollups"]["playbook_trust_write_count"] == 0
    assert data["rollups"]["gateway_queue_write_count"] == 0
    assert data["rollups"]["telegram_send_count"] == 0


def test_rejects_unmatched_24h_approvals(tmp_path):
    data = load_latest_ai_agent_matched_playbook_learning_gap()
    bad = copy.deepcopy(data)
    bad["production_readback"]["approval_24h_matched"] = 65
    bad["production_readback"]["matched_rate_24h_percent"] = 98
    bad["learning_gap_truth"]["approval_24h_matched"] = 65
    bad["rollups"]["approval_24h_matched"] = 65
    bad["rollups"]["matched_rate_24h_percent"] = 98
    _write_snapshot(tmp_path, bad)

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


def test_rejects_playbook_trust_write_enabled(tmp_path):
    data = load_latest_ai_agent_matched_playbook_learning_gap()
    bad = copy.deepcopy(data)
    bad["learning_gap_truth"]["playbook_trust_write_enabled"] = True
    _write_snapshot(tmp_path, bad)

    with pytest.raises(ValueError, match="live write/send/execution flags"):
        load_latest_ai_agent_matched_playbook_learning_gap(tmp_path)


def test_rejects_playbook_updated_24h(tmp_path):
    data = load_latest_ai_agent_matched_playbook_learning_gap()
    bad = copy.deepcopy(data)
    bad["production_readback"]["playbook_updated_24h"] = 1
    bad["learning_gap_truth"]["playbook_updated_24h"] = 1
    bad["rollups"]["playbook_updated_24h_count"] = 1
    _write_snapshot(tmp_path, bad)

    with pytest.raises(ValueError, match="playbook_updated_24h"):
        load_latest_ai_agent_matched_playbook_learning_gap(tmp_path)


def test_rejects_lane_live_write(tmp_path):
    data = load_latest_ai_agent_matched_playbook_learning_gap()
    bad = copy.deepcopy(data)
    bad["gap_lanes"][0]["live_write_enabled"] = True
    _write_snapshot(tmp_path, bad)

    with pytest.raises(ValueError, match="live_write_enabled"):
        load_latest_ai_agent_matched_playbook_learning_gap(tmp_path)


def test_rejects_gate_runtime_write(tmp_path):
    data = load_latest_ai_agent_matched_playbook_learning_gap()
    bad = copy.deepcopy(data)
    bad["learning_gates"][0]["creates_runtime_write"] = True
    _write_snapshot(tmp_path, bad)

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


def test_rejects_candidate_runtime_writer(tmp_path):
    data = load_latest_ai_agent_matched_playbook_learning_gap()
    bad = copy.deepcopy(data)
    bad["writeback_candidates"][0]["runtime_writer_enabled"] = True
    _write_snapshot(tmp_path, bad)

    with pytest.raises(ValueError, match="runtime_writer_enabled"):
        load_latest_ai_agent_matched_playbook_learning_gap(tmp_path)


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

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