"""Pattern: redact before you remember.

Memory turns one-off leaks into permanent ones. Scrub obvious secrets and
personal data before anything is written to long-term storage. Regexes catch
common formats only; treat this as a safety net, not a guarantee.
"""
from __future__ import annotations

import re

_RULES: list[tuple[str, re.Pattern]] = [
    ("PRIVATE_KEY", re.compile(r"-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]+?-----END [A-Z ]*PRIVATE KEY-----")),
    ("AWS_KEY", re.compile(r"\bAKIA[0-9A-Z]{16}\b")),
    ("GITHUB_TOKEN", re.compile(r"\bgh[pousr]_[A-Za-z0-9]{36,}\b")),
    ("API_KEY", re.compile(r"\bsk-[A-Za-z0-9_-]{20,}\b")),
    ("JWT", re.compile(r"\beyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\b")),
    ("EMAIL", re.compile(r"\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b")),
    ("CARD", re.compile(r"\b(?:\d[ -]?){13,19}\b")),
    ("PHONE", re.compile(r"(?<!\w)\+?\d{1,3}[ .-]?\(?\d{2,4}\)?[ .-]?\d{3,4}[ .-]?\d{3,4}\b")),
    ("SECRET_ASSIGNMENT", re.compile(r"(?i)\b(password|passwd|secret|token|api[_-]?key)\s*[:=]\s*\S+")),
]


def redact(text: str) -> str:
    """Replace sensitive substrings with [REDACTED:<TYPE>] markers."""
    out = text
    for label, pattern in _RULES:
        if label == "SECRET_ASSIGNMENT":
            out = pattern.sub(lambda m: f"{m.group(1)}=[REDACTED:SECRET]", out)
        else:
            out = pattern.sub(f"[REDACTED:{label}]", out)
    return out
