"""PII (Personally Identifiable Information) scanner."""

import re

from bilgeai.analyzer.models import PIIFinding
from bilgeai.core.constants import PII_PATTERNS


def scan_for_pii(rows: list[dict]) -> list[PIIFinding]:
    """Scan dataset rows for PII patterns."""
    findings: dict[str, list[int]] = {pii_type: [] for pii_type in PII_PATTERNS}

    compiled = {pii_type: re.compile(pattern) for pii_type, pattern in PII_PATTERNS.items()}

    for i, row in enumerate(rows):
        text = " ".join(str(v) for v in row.values())
        for pii_type, regex in compiled.items():
            if regex.search(text):
                findings[pii_type].append(i)

    results = []
    for pii_type, indices in findings.items():
        if indices:
            results.append(
                PIIFinding(
                    pii_type=pii_type,
                    count=len(indices),
                    sample_indices=indices[:5],
                )
            )
    return results
