"""
Unit Tests for Timeout Manager
"""

import pytest
import time
from altrus.core.intent.intent import Intent, IntentPriority
from altrus.core.intent.timeout_manager import TimeoutManager, TimeoutConfig

@pytest.fixture
def timeout_manager():
    config = TimeoutConfig(default_timeout=0.2)
    manager = TimeoutManager(config=config)
    yield manager
    manager.shutdown()

def test_timeout_tracking(timeout_manager):
    """Test basic timeout tracking logic"""
    intent = Intent("i1", "test", "cap.a", IntentPriority.NORMAL)

    timeout_manager.start_tracking(intent)
    assert timeout_manager.get_elapsed_time("i1") is not None

    time.sleep(0.3)
    assert timeout_manager.check_timeout(intent) is True

    timeout_manager.stop_tracking("i1")
    assert timeout_manager.get_elapsed_time("i1") is None

def test_capability_specific_timeout():
    """Test per-capability timeout overrides"""
    config = TimeoutConfig(
        default_timeout=10.0,
        capability_timeouts={"fast.cap": 0.1}
    )
    manager = TimeoutManager(config=config)

    fast_intent = Intent("i1", "fast", "fast.cap", IntentPriority.NORMAL)
    slow_intent = Intent("i2", "slow", "slow.cap", IntentPriority.NORMAL)

    manager.start_tracking(fast_intent)
    manager.start_tracking(slow_intent)

    time.sleep(0.2)
    assert manager.check_timeout(fast_intent) is True
    assert manager.check_timeout(slow_intent) is False

    manager.shutdown()

def test_timeout_callback(timeout_manager):
    """Test that timeout callbacks are triggered"""
    results = []
    def on_timeout(intent_id, elapsed):
        results.append(intent_id)

    timeout_manager.register_timeout_callback(on_timeout)

    intent = Intent("i1", "test", "cap.a", IntentPriority.NORMAL)
    timeout_manager.start_tracking(intent)

    # Wait for monitor thread to detect timeout
    # Default window in test_manager is 0.2s, monitor checks every 1.0s in real impl
    # I'll wait enough time
    time.sleep(1.5)

    assert "i1" in results
    assert timeout_manager.get_metrics()["total_timeouts"] >= 1
