"""
spidercrypt.pii
~~~~~~~~~~~~~~~
PII detection and masking utilities.
"""

import re
from pathlib import Path
from typing import Dict

from .patterns import PII_PATTERNS


def mask_text(text: str, patterns: Dict[str, str] = None) -> str:
    """
    Replace all PII occurrences in *text* with ``[TYPE]`` tokens.

    Args:
        text:     Input string to redact.
        patterns: Optional override for :data:`~spidercrypt.patterns.PII_PATTERNS`.

    Returns:
        Redacted string.
    """
    active = patterns or PII_PATTERNS
    for name, pat in active.items():
        text = re.sub(pat, f"[{name}]", text)
    return text


def mask_file(infile: str, outfile: str = None) -> str:
    """
    Redact PII in *infile*.

    Args:
        infile:  Path to source file.
        outfile: Optional path to write redacted content.
                 If omitted, the redacted text is returned only.

    Returns:
        Redacted text.
    """
    text = Path(infile).read_text(encoding="utf-8", errors="replace")
    redacted = mask_text(text)
    if outfile:
        Path(outfile).write_text(redacted, encoding="utf-8")
    return redacted