"""Tests for AnomalyTracker."""
import pytest
from scandar_guard.anomaly import AnomalyTracker


def test_no_findings_on_normal_tool_use():
    tracker = AnomalyTracker("test_session")
    # Normal usage — same tools used repeatedly
    for _ in range(5):
        findings = tracker.record_tool_call("search_database")
        assert len(findings) == 0


def test_new_tool_mid_session_flagged():
    tracker = AnomalyTracker("test_session")
    # Establish a pattern with 3+ unique tools
    tracker.record_tool_call("read_file")
    tracker.record_tool_call("search_database")
    tracker.record_tool_call("list_files")
    # Now introduce a new tool
    findings = tracker.record_tool_call("send_email")
    assert any(f.category == "NEW_TOOL_MID_SESSION" for f in findings)
    assert any(f.severity == "info" for f in findings)


def test_no_new_tool_warning_early_in_session():
    tracker = AnomalyTracker("test_session")
    # Only 2 unique tools seen — too early to flag
    tracker.record_tool_call("read_file")
    tracker.record_tool_call("search")
    findings = tracker.record_tool_call("new_tool")
    assert not any(f.category == "NEW_TOOL_MID_SESSION" for f in findings)


def test_suspicious_sequence_read_then_http():
    tracker = AnomalyTracker("test_session")
    tracker.record_tool_call("read_file")
    findings = tracker.record_tool_call("http_request")
    assert any(f.category == "DATA_EXFIL_SEQUENCE" for f in findings)
    assert any(f.severity == "high" for f in findings)


def test_suspicious_sequence_bash_then_http():
    tracker = AnomalyTracker("test_session")
    tracker.record_tool_call("bash")
    findings = tracker.record_tool_call("http_request")
    assert any(f.category == "COMMAND_THEN_EXFIL" for f in findings)
    assert any(f.severity == "critical" for f in findings)


def test_no_false_positive_on_normal_sequence():
    tracker = AnomalyTracker("test_session")
    tracker.record_tool_call("search_database")
    findings = tracker.record_tool_call("format_results")
    # Neither of these is a suspicious sequence
    seq_findings = [f for f in findings if f.category.endswith("_SEQUENCE") or f.category.endswith("_EXFIL")]
    assert len(seq_findings) == 0


def test_repeated_tool_not_flagged_as_new():
    tracker = AnomalyTracker("test_session")
    tracker.record_tool_call("read_file")
    tracker.record_tool_call("search_database")
    tracker.record_tool_call("list_files")
    tracker.record_tool_call("send_email")  # This gets flagged as new
    # Calling send_email again should NOT be flagged again
    findings = tracker.record_tool_call("send_email")
    assert not any(f.category == "NEW_TOOL_MID_SESSION" for f in findings)
