from __future__ import annotations

import copy
import json
import os
from pathlib import Path

import pytest

os.environ.setdefault("DATABASE_URL", "postgresql+asyncpg://test:test@localhost/test")

from src.services.ai_agent_12_agent_war_room import (
    load_latest_ai_agent_12_agent_war_room,
)


def test_load_latest_ai_agent_12_agent_war_room_snapshot() -> None:
    snapshot = load_latest_ai_agent_12_agent_war_room()

    assert snapshot["schema_version"] == "ai_agent_12_agent_war_room_v1"
    assert snapshot["program_status"]["current_task_id"] == "P2-142"
    assert snapshot["program_status"]["next_task_id"] == "P2-143"
    assert snapshot["program_status"]["overall_completion_percent"] == 72
    assert snapshot["program_status"]["runtime_authority"] == "12_agent_war_room_read_only_no_live_write"
    assert len(snapshot["agent_roles"]) == 12

    rollups = snapshot["rollups"]
    assert rollups["agent_role_count"] == 12
    assert rollups["read_only_review_completed_count"] == 12
    assert rollups["subagent_batch_limit"] == 6
    assert rollups["subagent_batch_count"] == 2
    assert rollups["total_work_units"] == 82
    assert rollups["total_evidence_items"] == 84
    assert rollups["approval_required_total"] == 61
    assert rollups["blocker_total"] == 54
    assert rollups["live_write_count"] == 0
    assert rollups["telegram_send_count"] == 0
    assert rollups["bot_api_call_count"] == 0
    assert rollups["production_write_count"] == 0
    assert rollups["paid_api_call_count"] == 0
    assert rollups["sdk_install_count"] == 0


def test_war_room_contract_keeps_reports_market_and_telegram_read_only() -> None:
    snapshot = load_latest_ai_agent_12_agent_war_room()

    assert snapshot["coordination_model"]["arbiter"] == "openclaw"
    assert snapshot["reporting_contract"]["daily"]["required"] is True
    assert snapshot["reporting_contract"]["weekly"]["required"] is True
    assert snapshot["reporting_contract"]["monthly"]["required"] is True
    assert len(snapshot["market_watch_contract"]["p0_refresh_candidates"]) == 5
    assert snapshot["telegram_contract"]["direct_send_allowed"] is False
    assert snapshot["telegram_contract"]["bot_api_call_allowed"] is False
    assert snapshot["telegram_contract"]["dedup_required"] is True
    assert snapshot["telegram_contract"]["receipt_required"] is True
    assert snapshot["display_redaction_contract"]["conversation_transcript_display_allowed"] is False
    assert snapshot["display_redaction_contract"]["secret_value_display_allowed"] is False


def test_rejects_missing_agent_role(tmp_path: Path) -> None:
    snapshot = copy.deepcopy(load_latest_ai_agent_12_agent_war_room())
    snapshot["agent_roles"] = snapshot["agent_roles"][:-1]
    snapshot["rollups"]["agent_role_count"] = 11
    snapshot["rollups"]["read_only_review_completed_count"] = 11
    _write_snapshot(tmp_path, snapshot)

    with pytest.raises(ValueError, match="expected exactly 12 agent roles"):
        load_latest_ai_agent_12_agent_war_room(tmp_path)


def test_rejects_role_live_write_drift(tmp_path: Path) -> None:
    snapshot = copy.deepcopy(load_latest_ai_agent_12_agent_war_room())
    snapshot["agent_roles"][0]["live_write_count"] = 1
    _write_snapshot(tmp_path, snapshot)

    with pytest.raises(ValueError, match="live_write_count must remain zero"):
        load_latest_ai_agent_12_agent_war_room(tmp_path)


def test_rejects_telegram_direct_send_drift(tmp_path: Path) -> None:
    snapshot = copy.deepcopy(load_latest_ai_agent_12_agent_war_room())
    snapshot["telegram_contract"]["direct_send_allowed"] = True
    _write_snapshot(tmp_path, snapshot)

    with pytest.raises(ValueError, match="direct_send_allowed must remain false"):
        load_latest_ai_agent_12_agent_war_room(tmp_path)


def test_rejects_forbidden_public_terms(tmp_path: Path) -> None:
    snapshot = copy.deepcopy(load_latest_ai_agent_12_agent_war_room())
    snapshot["agent_roles"][0]["next_action"] = "blocked source_thread_id leak"
    _write_snapshot(tmp_path, snapshot)

    with pytest.raises(ValueError, match="forbidden public terms leaked"):
        load_latest_ai_agent_12_agent_war_room(tmp_path)


def _write_snapshot(directory: Path, payload: dict) -> None:
    path = directory / "ai_agent_12_agent_war_room_2099-01-01.json"
    path.write_text(json.dumps(payload, ensure_ascii=False), encoding="utf-8")
