import copy

import pytest

from src.services.ai_agent_telegram_receipt_approval_package import (
    load_latest_ai_agent_telegram_receipt_approval_package,
)


def test_load_latest_ai_agent_telegram_receipt_approval_package():
    data = load_latest_ai_agent_telegram_receipt_approval_package()

    assert data["schema_version"] == "ai_agent_telegram_receipt_approval_package_v1"
    assert data["program_status"]["current_task_id"] == "P2-403E"
    assert data["program_status"]["next_task_id"] == "P2-403F"
    assert data["telegram_truth"]["telegram_send_allowed"] is False
    assert data["telegram_truth"]["gateway_queue_write_allowed"] is False
    assert data["telegram_truth"]["live_delivered_receipt_count"] == 0
    assert data["rollups"]["receipt_gate_count"] == len(data["receipt_gates"])


def test_rejects_telegram_send_enabled(tmp_path):
    data = load_latest_ai_agent_telegram_receipt_approval_package()
    bad = copy.deepcopy(data)
    bad["telegram_truth"]["telegram_send_allowed"] = True
    path = tmp_path / "ai_agent_telegram_receipt_approval_package_2026-06-11.json"
    path.write_text(__import__("json").dumps(bad), encoding="utf-8")

    with pytest.raises(ValueError, match="Telegram truth flags"):
        load_latest_ai_agent_telegram_receipt_approval_package(tmp_path)


def test_rejects_missing_delivery_receipt(tmp_path):
    data = load_latest_ai_agent_telegram_receipt_approval_package()
    bad = copy.deepcopy(data)
    bad["receipt_package"]["delivery_receipt_required"] = False
    path = tmp_path / "ai_agent_telegram_receipt_approval_package_2026-06-11.json"
    path.write_text(__import__("json").dumps(bad), encoding="utf-8")

    with pytest.raises(ValueError, match="delivery receipt"):
        load_latest_ai_agent_telegram_receipt_approval_package(tmp_path)


def test_rejects_rollup_mismatch(tmp_path):
    data = load_latest_ai_agent_telegram_receipt_approval_package()
    bad = copy.deepcopy(data)
    bad["rollups"]["receipt_gate_count"] = 999
    path = tmp_path / "ai_agent_telegram_receipt_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_telegram_receipt_approval_package(tmp_path)
