"""Tests for PIICheck."""

from unittest.mock import MagicMock, patch

from ai_qa.checks.pii import PIICheck
from ai_qa.core.context import Context
from ai_qa.exceptions import ContextValidationError


def test_pii_check_name():
    """Test PIICheck has correct name."""
    check = PIICheck()
    assert check.name == "pii"


def test_pii_check_requires_llm():
    """Test PIICheck requires_llm property."""
    check = PIICheck()
    assert check.requires_llm is False


def test_pii_email_detection():
    """Test email address detection."""
    check = PIICheck()
    ctx = Context(output="Contact me at john.doe@example.com for more info")
    result = check.evaluate(ctx)
    assert result.score == 0.0
    assert "email" in result.evidence


def test_pii_ssn_detection():
    """Test SSN pattern detection."""
    check = PIICheck()
    ctx = Context(output="My SSN is 123-45-6789")
    result = check.evaluate(ctx)
    assert result.score == 0.0
    assert "ssn" in result.evidence


def test_pii_phone_detection():
    """Test phone number detection."""
    check = PIICheck()
    ctx = Context(output="Call me at 555-123-4567")
    result = check.evaluate(ctx)
    assert result.score == 0.0
    assert "phone" in result.evidence


def test_pii_no_pii():
    """Test clean output (no PII)."""
    check = PIICheck()
    ctx = Context(output="This is a clean message with no sensitive data")
    result = check.evaluate(ctx)
    assert result.score == 1.0
    assert result.passed


def test_pii_multiple_types():
    """Test detection of multiple PII types."""
    check = PIICheck()
    ctx = Context(
        output="Email: test@example.com, Phone: 555-123-4567, SSN: 123-45-6789"
    )
    result = check.evaluate(ctx)
    assert result.score == 0.0


def test_pii_no_output():
    """Test error when output missing."""
    import pytest

    check = PIICheck()
    # Create a context with MagicMock to simulate missing output
    from unittest.mock import MagicMock

    ctx = MagicMock()
    ctx.output = None
    with pytest.raises(ContextValidationError):
        check.evaluate(ctx)


@patch("ai_qa.checks.pii.get_provider")
def test_pii_with_llm_enhancement(mock_get_provider):
    """Test LLM-enhanced PII detection."""
    check = PIICheck(use_llm=True)
    assert check.requires_llm is True

    ctx = Context(output="Dr. Smith works at Johns Hopkins")

    mock_provider = MagicMock()
    mock_provider.judge.return_value = {
        "score": 0.8,
        "evidence": "Name detected",
    }
    mock_get_provider.return_value = mock_provider

    result = check.evaluate(ctx)
    assert result.score == 0.8
