# tests/test_wave1_multiagent.py
"""Tests for MultiAgentSimulator (wave1 29.9)."""
from __future__ import annotations

import sys
from pathlib import Path
import pytest
import numpy as np

ROOT = Path(__file__).resolve().parent.parent
sys.path.insert(0, str(ROOT))


def test_import():
    from llm_guard.infrastructure.multiagent_simulator import MultiAgentSimulator
    assert MultiAgentSimulator is not None


def test_instantiates():
    from llm_guard.infrastructure.multiagent_simulator import MultiAgentSimulator
    sim = MultiAgentSimulator()
    assert sim.n_trials == 1000
    assert sim.seed == 42


def test_simulate_returns_result():
    from llm_guard.infrastructure.multiagent_simulator import MultiAgentSimulator, SimulationResult
    sim = MultiAgentSimulator(n_trials=100)
    result = sim.simulate(p1_error=0.3, p2_base_error=0.4, correlation=0.0)
    assert isinstance(result, SimulationResult)


def test_simulation_result_fields():
    from llm_guard.infrastructure.multiagent_simulator import MultiAgentSimulator, SimulationResult
    sim = MultiAgentSimulator(n_trials=100)
    r = sim.simulate(p1_error=0.3, p2_base_error=0.4, correlation=0.0)
    assert hasattr(r, "p1_error")
    assert hasattr(r, "p2_given_correct")
    assert hasattr(r, "p2_given_wrong")
    assert hasattr(r, "joint_failure_rate")
    assert hasattr(r, "independent_expected")
    assert hasattr(r, "independence_p_value")
    assert hasattr(r, "correlation_coefficient")


def test_independence_holds_when_correlation_zero():
    """With correlation=0, joint failure should be approximately p1*p2."""
    from llm_guard.infrastructure.multiagent_simulator import MultiAgentSimulator
    sim = MultiAgentSimulator(n_trials=5000, seed=0)
    r = sim.simulate(p1_error=0.3, p2_base_error=0.3, correlation=0.0)
    expected = 0.3 * 0.3
    assert abs(r.joint_failure_rate - expected) < 0.05, (
        f"Expected ~{expected:.3f}, got {r.joint_failure_rate:.3f}"
    )


def test_correlation_increases_joint_failure():
    """High correlation should increase joint failure rate above p1*p2."""
    from llm_guard.infrastructure.multiagent_simulator import MultiAgentSimulator
    sim = MultiAgentSimulator(n_trials=5000, seed=42)
    r_independent = sim.simulate(p1_error=0.3, p2_base_error=0.4, correlation=0.0)
    r_correlated   = sim.simulate(p1_error=0.3, p2_base_error=0.4, correlation=0.5)
    assert r_correlated.joint_failure_rate > r_independent.joint_failure_rate


def test_simulate_batch_returns_list():
    from llm_guard.infrastructure.multiagent_simulator import MultiAgentSimulator
    sim = MultiAgentSimulator(n_trials=100)
    results = sim.simulate_batch(p1_errors=[0.1, 0.3, 0.5], p2_base_error=0.4)
    assert len(results) == 3
