"""Tests for PII detection and redaction."""

import sys
sys.path.insert(0, ".")

from agent_shield import pii


def test_detect_email():
    matches = pii.detect("Contact me at john@example.com")
    assert len(matches) == 1
    assert matches[0].type == "EMAIL"
    assert matches[0].value == "john@example.com"


def test_detect_nigerian_phone():
    matches = pii.detect("Call 08034567890")
    assert any(m.type == "PHONE_NG" for m in matches)


def test_detect_bvn():
    matches = pii.detect("My BVN: 12345678901")
    assert any(m.type == "BVN" for m in matches)


def test_detect_uk_ni():
    matches = pii.detect("NI number AB123456C")
    assert any(m.type == "NI_NUMBER_UK" for m in matches)


def test_detect_credit_card():
    matches = pii.detect("Card: 4111-1111-1111-1111")
    assert any(m.type == "CREDIT_CARD" for m in matches)


def test_detect_dob():
    matches = pii.detect("DOB: 15/03/1990")
    assert any(m.type == "DATE_OF_BIRTH" for m in matches)


def test_detect_ip():
    matches = pii.detect("IP: 192.168.1.100")
    assert any(m.type == "IP_ADDRESS" for m in matches)


def test_redact():
    text = "Email john@test.com or call 08012345678"
    redacted = pii.redact(text)
    assert "john@test.com" not in redacted
    assert "08012345678" not in redacted
    assert "[EMAIL_REDACTED]" in redacted
    assert "[PHONE_REDACTED]" in redacted


def test_no_pii():
    assert not pii.contains_pii("Hello world, nice weather today")
    assert pii.detect("Just a normal sentence") == []


def test_summary():
    text = "Email a@b.com and b@c.com, phone 08012345678"
    s = pii.summary(text)
    assert s.get("EMAIL", 0) >= 1
    assert s.get("PHONE_NG", 0) == 1


def test_confidence_filter():
    # Low confidence should filter out DATE_GENERIC
    matches_high = pii.detect("Date: 15/03/2025", min_confidence=0.8)
    matches_low = pii.detect("Date: 15/03/2025", min_confidence=0.2)
    assert len(matches_low) >= len(matches_high)


def test_type_filter():
    text = "Email john@test.com phone 08012345678"
    matches = pii.detect(text, types=["EMAIL"])
    assert all(m.type == "EMAIL" for m in matches)


if __name__ == "__main__":
    for name, fn in list(globals().items()):
        if name.startswith("test_") and callable(fn):
            try:
                fn()
                print(f"  PASS {name}")
            except AssertionError as e:
                print(f"  FAIL {name}: {e}")
    print("Done.")
