import copy

import pytest

from src.services.ai_agent_learning_writeback_approval_package import (
    load_latest_ai_agent_learning_writeback_approval_package,
)


def test_load_latest_ai_agent_learning_writeback_approval_package():
    data = load_latest_ai_agent_learning_writeback_approval_package()

    assert data["schema_version"] == "ai_agent_learning_writeback_approval_package_v1"
    assert data["program_status"]["current_task_id"] == "P2-403D"
    assert data["program_status"]["next_task_id"] == "P2-403E"
    assert data["learning_truth"]["km_write_allowed"] is False
    assert data["learning_truth"]["playbook_trust_write_allowed"] is False
    assert data["learning_truth"]["live_learning_write_count"] == 0
    assert data["rollups"]["review_gate_count"] == len(data["review_gates"])


def test_rejects_learning_write_enabled(tmp_path):
    data = load_latest_ai_agent_learning_writeback_approval_package()
    bad = copy.deepcopy(data)
    bad["learning_truth"]["km_write_allowed"] = True
    path = tmp_path / "ai_agent_learning_writeback_approval_package_2026-06-11.json"
    path.write_text(__import__("json").dumps(bad), encoding="utf-8")

    with pytest.raises(ValueError, match="learning truth flags"):
        load_latest_ai_agent_learning_writeback_approval_package(tmp_path)


def test_rejects_missing_owner_review(tmp_path):
    data = load_latest_ai_agent_learning_writeback_approval_package()
    bad = copy.deepcopy(data)
    bad["writeback_package"]["owner_review_required"] = False
    path = tmp_path / "ai_agent_learning_writeback_approval_package_2026-06-11.json"
    path.write_text(__import__("json").dumps(bad), encoding="utf-8")

    with pytest.raises(ValueError, match="owner review"):
        load_latest_ai_agent_learning_writeback_approval_package(tmp_path)


def test_rejects_rollup_mismatch(tmp_path):
    data = load_latest_ai_agent_learning_writeback_approval_package()
    bad = copy.deepcopy(data)
    bad["rollups"]["review_gate_count"] = 999
    path = tmp_path / "ai_agent_learning_writeback_approval_package_2026-06-11.json"
    path.write_text(__import__("json").dumps(bad), encoding="utf-8")

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