import copy
import json

import pytest

from src.services.ai_agent_task_result_audit_trail import (
    load_latest_ai_agent_task_result_audit_trail,
)


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


def test_load_latest_ai_agent_task_result_audit_trail():
    data = load_latest_ai_agent_task_result_audit_trail()

    assert data["schema_version"] == "ai_agent_task_result_audit_trail_v1"
    assert data["program_status"]["current_task_id"] == "P2-103"
    assert data["program_status"]["next_task_id"] == "P2-104"
    assert data["program_status"]["overall_completion_percent"] == 99
    assert data["result_audit_truth"]["task_result_route_matrix_ready"] is True
    assert data["result_audit_truth"]["km_draft_contract_ready"] is True
    assert data["result_audit_truth"]["logbook_append_contract_ready"] is True
    assert data["result_audit_truth"]["audit_trail_contract_ready"] is True
    assert data["result_audit_truth"]["runtime_execution_enabled"] is False
    assert data["result_audit_truth"]["km_write_enabled"] is False
    assert data["result_audit_truth"]["logbook_runtime_write_enabled"] is False
    assert data["result_audit_truth"]["audit_db_write_enabled"] is False
    assert data["result_audit_truth"]["timeline_write_enabled"] is False
    assert data["result_audit_truth"]["gateway_queue_write_enabled"] is False
    assert data["result_audit_truth"]["telegram_send_enabled"] is False
    assert data["rollups"]["result_route_count"] == 8
    assert data["rollups"]["owner_next_action_ready_count"] == 8
    assert data["rollups"]["requires_owner_review_count"] == 7
    assert data["rollups"]["ready_for_km_draft_count"] == 5
    assert data["rollups"]["blocked_result_count"] == 3
    assert data["rollups"]["writeback_contract_count"] == 6
    assert data["rollups"]["audit_checkpoint_count"] == 7
    assert data["rollups"]["operator_handoff_count"] == 5
    assert data["rollups"]["runtime_execution_count"] == 0
    assert data["rollups"]["km_write_count"] == 0
    assert data["rollups"]["logbook_runtime_write_count"] == 0
    assert data["rollups"]["audit_db_write_count"] == 0
    assert data["rollups"]["timeline_write_count"] == 0
    assert data["rollups"]["gateway_queue_write_count"] == 0
    assert data["rollups"]["telegram_send_count"] == 0


def test_rejects_km_write_enabled(tmp_path):
    data = load_latest_ai_agent_task_result_audit_trail()
    bad = copy.deepcopy(data)
    bad["result_audit_truth"]["km_write_enabled"] = True
    _write_snapshot(tmp_path, bad)

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


def test_rejects_audit_db_write_count(tmp_path):
    data = load_latest_ai_agent_task_result_audit_trail()
    bad = copy.deepcopy(data)
    bad["result_audit_truth"]["audit_db_write_count_24h"] = 1
    bad["rollups"]["audit_db_write_count"] = 1
    _write_snapshot(tmp_path, bad)

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


def test_rejects_result_route_live_write(tmp_path):
    data = load_latest_ai_agent_task_result_audit_trail()
    bad = copy.deepcopy(data)
    bad["result_routes"][0]["writes_live_state"] = True
    _write_snapshot(tmp_path, bad)

    with pytest.raises(ValueError, match="writes_live_state"):
        load_latest_ai_agent_task_result_audit_trail(tmp_path)


def test_rejects_result_route_without_next_action(tmp_path):
    data = load_latest_ai_agent_task_result_audit_trail()
    bad = copy.deepcopy(data)
    bad["result_routes"][0]["operator_next_action"] = ""
    bad["rollups"]["owner_next_action_ready_count"] = 7
    _write_snapshot(tmp_path, bad)

    with pytest.raises(ValueError, match="operator_next_action"):
        load_latest_ai_agent_task_result_audit_trail(tmp_path)


def test_rejects_writeback_contract_runtime_writer(tmp_path):
    data = load_latest_ai_agent_task_result_audit_trail()
    bad = copy.deepcopy(data)
    bad["writeback_contracts"][0]["runtime_writer_enabled"] = True
    _write_snapshot(tmp_path, bad)

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


def test_rejects_checkpoint_runtime_action(tmp_path):
    data = load_latest_ai_agent_task_result_audit_trail()
    bad = copy.deepcopy(data)
    bad["audit_checkpoints"][0]["creates_runtime_action"] = True
    _write_snapshot(tmp_path, bad)

    with pytest.raises(ValueError, match="creates_runtime_action"):
        load_latest_ai_agent_task_result_audit_trail(tmp_path)


def test_rejects_handoff_runtime_action(tmp_path):
    data = load_latest_ai_agent_task_result_audit_trail()
    bad = copy.deepcopy(data)
    bad["operator_handoffs"][0]["creates_runtime_action"] = True
    _write_snapshot(tmp_path, bad)

    with pytest.raises(ValueError, match="creates_runtime_action"):
        load_latest_ai_agent_task_result_audit_trail(tmp_path)


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

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