import copy
import json
from pathlib import Path

import pytest

from src.services.ai_agent_failure_receipt_no_send_replay import (
    load_latest_ai_agent_failure_receipt_no_send_replay,
)


REPO_ROOT = Path(__file__).resolve().parents[3]
FIXTURE = REPO_ROOT / "docs/evaluations/ai_agent_failure_receipt_no_send_replay_2026-06-13.json"


def test_load_latest_ai_agent_failure_receipt_no_send_replay_snapshot() -> None:
    data = load_latest_ai_agent_failure_receipt_no_send_replay()

    assert data["schema_version"] == "ai_agent_failure_receipt_no_send_replay_v1"
    assert data["program_status"]["current_task_id"] == "P2-116"
    assert data["program_status"]["next_task_id"] == "P2-117"
    assert data["program_status"]["overall_completion_percent"] == 100
    assert data["program_status"]["read_only_mode"] is True

    rollups = data["rollups"]
    assert rollups["no_send_replay_fixture_count"] == 5
    assert rollups["route_lock_check_count"] == 4
    assert rollups["replay_verifier_check_count"] == 5
    assert rollups["blocked_send_count"] == 5
    assert rollups["operator_action_count"] == 5
    assert rollups["approval_required_fixture_count"] == 2
    assert rollups["blocked_fixture_count"] == 2
    assert rollups["approval_required_route_lock_count"] == 1
    assert rollups["blocked_route_lock_count"] == 1
    assert rollups["approval_required_verifier_count"] == 2
    assert rollups["critical_blocker_count"] == 3

    assert {fixture["target_channel"] for fixture in data["no_send_replay_fixtures"]} == {"awoooi_sre_war_room"}
    assert {check["target_route"] for check in data["route_lock_checks"]} == {"awoooi_sre_war_room"}

    zero_fields = [
        "owner_approval_received_count",
        "canonical_runtime_target_read_count",
        "live_query_count",
        "failure_receipt_send_count",
        "gateway_queue_write_count",
        "telegram_send_count",
        "bot_api_call_count",
        "report_receipt_write_count",
        "reviewer_queue_write_count",
        "result_capture_write_count",
        "learning_write_count",
        "playbook_trust_write_count",
        "production_write_count",
        "secret_read_count",
        "destructive_operation_count",
    ]
    for field in zero_fields:
        assert rollups[field] == 0


def test_failure_receipt_no_send_replay_rejects_send_enabled(tmp_path: Path) -> None:
    source = json.loads(FIXTURE.read_text(encoding="utf-8"))
    source["no_send_replay_fixtures"][0]["send_enabled"] = True
    target = tmp_path / "ai_agent_failure_receipt_no_send_replay_2026-06-13.json"
    target.write_text(json.dumps(source), encoding="utf-8")

    with pytest.raises(ValueError, match="must not enable send"):
        load_latest_ai_agent_failure_receipt_no_send_replay(tmp_path)


def test_failure_receipt_no_send_replay_rejects_gateway_queue_write(tmp_path: Path) -> None:
    source = json.loads(FIXTURE.read_text(encoding="utf-8"))
    source["replay_truth"]["gateway_queue_write_enabled"] = True
    target = tmp_path / "ai_agent_failure_receipt_no_send_replay_2026-06-13.json"
    target.write_text(json.dumps(source), encoding="utf-8")

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


def test_failure_receipt_no_send_replay_rejects_route_drift(tmp_path: Path) -> None:
    source = json.loads(FIXTURE.read_text(encoding="utf-8"))
    source["route_lock_checks"][0]["target_route"] = "legacy_alert_room"
    target = tmp_path / "ai_agent_failure_receipt_no_send_replay_2026-06-13.json"
    target.write_text(json.dumps(source), encoding="utf-8")

    with pytest.raises(ValueError, match="must target awoooi_sre_war_room"):
        load_latest_ai_agent_failure_receipt_no_send_replay(tmp_path)


def test_failure_receipt_no_send_replay_rejects_rollup_drift(tmp_path: Path) -> None:
    source = json.loads(FIXTURE.read_text(encoding="utf-8"))
    source["rollups"]["no_send_replay_fixture_count"] = 4
    target = tmp_path / "ai_agent_failure_receipt_no_send_replay_2026-06-13.json"
    target.write_text(json.dumps(source), encoding="utf-8")

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


def test_failure_receipt_no_send_replay_rejects_forbidden_display_terms(tmp_path: Path) -> None:
    source = copy.deepcopy(json.loads(FIXTURE.read_text(encoding="utf-8")))
    source["operator_actions"][0]["operator_instruction"] = "do not expose session_id"
    target = tmp_path / "ai_agent_failure_receipt_no_send_replay_2026-06-13.json"
    target.write_text(json.dumps(source), encoding="utf-8")

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