# utils/vault_markdown_sanitize.py — Parity with VaultMarkdownCodec.sanitizedPlainMarkdown (Swift).
from __future__ import annotations

import re

_UNSAFE_IMAGE = re.compile(r"!\[[^\]\n]*\]\(\s*(?:https?://|file://)[^)]+\)", re.IGNORECASE)
_LOCAL_URL = re.compile(
    r"https?://(?:localhost|127\.0\.0\.1)(?::\d+)?/[^\s)\]]+",
    re.IGNORECASE,
)
_TOKEN_LEAK = re.compile(
    r'(?i)\b(?:x-auth-token|authorization|api[_-]?key|token|password|secret)\s*[:=]\s*[^\s,;)]+|"X-Auth-Token"\s*:\s*"[^"]+"',
)


def sanitize_vault_markdown_for_storage(text: str) -> str:
    """Strip patterns Swift removes before persisting Vault note bodies."""
    out = str(text or "")
    out = _UNSAFE_IMAGE.sub("[Image removed: external image URL]", out)
    out = _LOCAL_URL.sub("[local vault URL removed]", out)
    out = _TOKEN_LEAK.sub("[redacted]", out)
    return out
