"""回调 answer 预览的凭证脱敏规则。"""

from __future__ import annotations

import re
from collections.abc import Collection
from typing import Any

_SECRET_KEY_RE = re.compile(
    r"(?i)(?:^|_)(?:token|secret|password|passwd|api_key|authorization|cookie)$",
)

_ANSI_RE = re.compile(r"\x1b\[[0-9;]*[A-Za-z]")
_BEARER_RE = re.compile(
    r"(?i)(\b(?:authorization\s*[:=]\s*)?(?:bearer|basic)\s+)[^\s,;'\"<>]+",
)
_COOKIE_RE = re.compile(r"(?i)(\b(?:set-)?cookie\s*[:=]\s*)[^\r\n]+")
_JSON_SECRET_RE = re.compile(
    r'''(?ix)
    ("(?:password|passwd|token|secret|authorization|api[_ -]?key|cookie)"\s*:\s*")
    ([^"]*)
    (")
    ''',
)
# 复合凭证键任意值全拦;裸 token 键要求值 >=15 字符(真凭证都 >=15)。
_ASSIGNMENT_RE = re.compile(
    r'''(?ix)
    (\b(?:password|passwd|secret|authorization|api[_ -]?key|(?:access|refresh|private|auth|session|bearer|csrf|reset)[ _-]token)\b\s*[:=]\s*)
    (?:"[^"]*"|'[^']*'|[^\s,;]+)
    |
    (\btoken\b\s*[:=]\s*)
    (?:"[^"]{15,}"|'[^']{15,}'|[^\s,;]{15,})
    ''',
    re.VERBOSE,
)
# 不加 (?i):防吞 max_tokens= 等普通配置赋值。
_ENV_ASSIGNMENT_RE = re.compile(
    r'''(\b[A-Z][A-Z0-9_]*(?:TOKEN|KEY|SECRET|PASSWORD|PASSWD)\s*=\s*)
    (?:"[^"]*"|'[^']*'|[^\s,;]+)
    ''',
    re.VERBOSE,
)
_ENV_SET_STATUS_RE = re.compile(
    r'''\b([A-Z][A-Z0-9_]*(?:TOKEN|KEY|SECRET|PASSWORD|PASSWD)
    \s+is\s+set:\s*yes)
    [^\s,;]+''',
    re.VERBOSE,
)
_QUERY_TOKEN_RE = re.compile(
    r"(?i)([?&](?:access_)?(?:token|api[_-]?key|secret|password)=)[^&\s]+",
)
_URL_CREDENTIAL_RE = re.compile(
    r"(?i)\b((?:https?|ssh|sftp)://)[^/@\s:]+:[^/@\s]+@"
)
_OPENAI_KEY_RE = re.compile(r"\bsk-[A-Za-z0-9_-]{20,}\b")
# 值须含数字+字母:纯数字长 ID(运行/请求号)无凭证熵不吞。
_ABBREV_SECRET_RE = re.compile(
    r'''(\b[A-Z][A-Z0-9]?(?:_[A-Z0-9]+){0,2}\s*=\s*)
    ((?=[A-Za-z0-9_-]{20,})
    (?=[A-Za-z0-9_-]*[0-9])
    (?=[A-Za-z0-9_-]*[A-Za-z])
    [A-Za-z0-9_-]{20,})''',
    re.VERBOSE,
)
_PRIVATE_KEY_RE = re.compile(
    r"-----BEGIN [^-]*PRIVATE KEY-----.*?-----END [^-]*PRIVATE KEY-----",
    re.DOTALL,
)

_SENSITIVE_VALUE_PATTERNS = (
    re.compile(
        r'''\b[A-Z][A-Z0-9_]*(?:TOKEN|KEY|SECRET|PASSWORD|PASSWD)
        \s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s,;]+))
        ''',
        re.VERBOSE,
    ),
    re.compile(
        r'''\b[A-Z][A-Z0-9_]*(?:TOKEN|KEY|SECRET|PASSWORD|PASSWD)
        \s+is\s+set:\s*yes([^\s,;]+)
        ''',
        re.VERBOSE,
    ),
    re.compile(
        r'''(?ix)\b(?:authorization\s*[:=]\s*)?(?:bearer|basic)\s+([^\s,;'"<>]+)''',
    ),
    re.compile(r"(?i)\b(?:https?|ssh|sftp)://[^/@\s:]+:([^/@\s]+)@"),
    re.compile(r"\b(sk-[A-Za-z0-9_-]{20,})\b"),
)


def collect_sensitive_values(value: Any, *, min_length: int = 8) -> frozenset[str]:
    """收集已知凭证值,供全文精确替换。"""
    collected: set[str] = set()

    def _collect(item: Any, key: str | None = None) -> None:
        if isinstance(item, dict):
            for child_key, child in item.items():
                _collect(child, str(child_key))
            return
        if isinstance(item, (list, tuple, set)):
            for child in item:
                _collect(child)
            return
        if not isinstance(item, str):
            return
        if key and _SECRET_KEY_RE.search(key) and len(item) >= min_length:
            collected.add(item)
        for pattern in _SENSITIVE_VALUE_PATTERNS:
            for match in pattern.finditer(item):
                candidate = next(
                    (group for group in match.groups() if group is not None),
                    "",
                )
                if len(candidate) >= min_length and "<redacted>" not in candidate:
                    collected.add(candidate)

    _collect(value)
    return frozenset(collected)


def redact_sensitive_text(
    value: str,
    sensitive_values: Collection[str] | None = None,
) -> str:
    """按键控/URL/私钥等模式替换为 <redacted>,键名保持可读。"""
    if not value:
        return ""
    cleaned = _ANSI_RE.sub("", str(value))
    for sensitive_value in sorted(sensitive_values or (), key=len, reverse=True):
        if sensitive_value:
            cleaned = cleaned.replace(sensitive_value, "<redacted>")
    cleaned = _PRIVATE_KEY_RE.sub("<redacted-private-key>", cleaned)
    cleaned = _BEARER_RE.sub(r"\1<redacted>", cleaned)
    cleaned = _COOKIE_RE.sub(r"\1<redacted>", cleaned)
    cleaned = _JSON_SECRET_RE.sub(r"\1<redacted>\3", cleaned)
    cleaned = _ENV_ASSIGNMENT_RE.sub(r"\1<redacted>", cleaned)
    cleaned = _ENV_SET_STATUS_RE.sub(r"\1<redacted>", cleaned)
    cleaned = _ASSIGNMENT_RE.sub(
        lambda m: (m.group(1) or m.group(2)) + "<redacted>", cleaned,
    )
    cleaned = _QUERY_TOKEN_RE.sub(r"\1<redacted>", cleaned)
    cleaned = _URL_CREDENTIAL_RE.sub(r"\1<redacted>@", cleaned)
    cleaned = _OPENAI_KEY_RE.sub("<redacted-api-key>", cleaned)
    cleaned = _ABBREV_SECRET_RE.sub(r"\1<redacted>", cleaned)
    return cleaned