"""
Unit tests for Intent Rules and Dead Letter Queue
"""
import pytest
from altrus.core.intent.preemption_engine import PreemptionRule
from altrus.core.intent.rules import PriorityBasedResolver
from altrus.core.intent.dead_letter import DeadLetterQueue, FailureReason
from altrus.core.intent.intent import Intent, IntentPriority, IntentState

def test_preemption_rules():
    """Test actual PreemptionRule evaluation from engine"""
    rule = PreemptionRule(
        name="priority_check",
        min_priority=IntentPriority.HIGH,
        capability_patterns=["nav.*"]
    )

    i1 = Intent("i1", "low_nav", "nav.move", IntentPriority.LOW)
    i2 = Intent("i2", "high_nav", "nav.move", IntentPriority.HIGH)
    i3 = Intent("i3", "high_tele", "tele.call", IntentPriority.HIGH)

    # Matches only if priority is HIGH and capability matches pattern
    assert rule.matches(i1) is False  # Priority too low
    assert rule.matches(i2) is True   # Priority OK, Pattern OK
    assert rule.matches(i3) is False  # Priority OK, Pattern No Match

def test_priority_based_resolver():
    """Test PriorityBasedResolver logic"""
    resolver = PriorityBasedResolver()

    i1 = Intent("i1", "low", "c1", IntentPriority.LOW)
    i2 = Intent("i2", "high", "c1", IntentPriority.HIGH)
    i3 = Intent("i3", "normal", "c1", IntentPriority.NORMAL)

    winner = resolver.resolve([i1, i2, i3])
    assert winner.intent_id == "i2"

def test_dead_letter_queue():
    """Test dead letter queue submission and retrieval"""
    dlq = DeadLetterQueue()

    intent = Intent("i1", "n1", "c1", IntentPriority.NORMAL)
    intent.state = IntentState.REJECTED

    dlq.add(intent, reason=FailureReason.UNKNOWN)

    entries = dlq.get_all()
    assert len(entries) == 1
    assert entries[0].intent.intent_id == "i1"
    assert entries[0].failure_reason == FailureReason.UNKNOWN

def test_dead_letter_clear():
    """Test clearing the queue"""
    dlq = DeadLetterQueue()
    intent = Intent("i1", "n1", "c1", IntentPriority.NORMAL)
    dlq.add(intent, reason=FailureReason.UNKNOWN)

    dlq.clear()
    assert len(dlq.get_all()) == 0
