"""PII detection service."""

import re
from typing import Dict, List
from dataclasses import dataclass


@dataclass
class PIIDetectionResult:
    """Result of PII detection."""

    has_pii: bool
    pii_types: List[str]
    total_matches: int
    details: Dict[str, List[str]]


class PIIDetector:
    """Service for detecting PII in messages."""

    # Regex patterns for common PII
    PATTERNS = {
        "email": r"\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b",
        "ssn": r"\b\d{3}-\d{2}-\d{4}\b",
        "credit_card": r"\b(?:\d[ -]*?){13,16}\b",
        "phone": r"\b\d{3}[-.]?\d{3}[-.]?\d{4}\b",
        "ip_address": r"\b(?:\d{1,3}\.){3}\d{1,3}\b",
    }

    def detect(self, message: str) -> PIIDetectionResult:
        """Detect PII in a message."""
        results = {}

        for pii_type, pattern in self.PATTERNS.items():
            matches = re.findall(pattern, message)
            if matches:
                results[pii_type] = matches

        return PIIDetectionResult(
            has_pii=len(results) > 0,
            pii_types=list(results.keys()),
            total_matches=sum(len(matches) for matches in results.values()),
            details=results,
        )

    def detect_simple(self, message: str) -> bool:
        """Simple PII detection - returns True if PII found."""
        # Quick check for email (most common)
        return "@" in message and ".com" in message


# Singleton instance
pii_detector = PIIDetector()
