import logging
import re

EMAIL_RE = re.compile(r"[\w\.-]+@[\w\.-]+", re.IGNORECASE)

class PiiRedactionFilter(logging.Filter):
    """Filter that redacts email addresses and long numeric IDs from log records."""

    def filter(self, record: logging.LogRecord) -> bool:
        if isinstance(record.msg, dict):
            # For structured logs we mutate in-place.
            record.msg = self._redact_dict(record.msg)
        elif isinstance(record.msg, str):
            record.msg = self._redact_text(record.msg)
        return True  # Always log, but redacted

    def _redact_text(self, text: str) -> str:
        text = EMAIL_RE.sub("<redacted-email>", text)
        # Redact numeric IDs longer than 6 digits
        text = re.sub(r"(?<!\d)(\d{7,})(?!\d)", "<id>", text)
        return text

    def _redact_dict(self, data):
        redacted = {}
        for k, v in data.items():
            if isinstance(v, str):
                redacted[k] = self._redact_text(v)
            else:
                redacted[k] = v
        return redacted 