import logging
import re


class APIKeyFilter(logging.Filter):
    """日志过滤器，拦截敏感信息"""

    PATTERNS = [
        (r'key=[A-Za-z0-9_-]{30,}', 'key=***REDACTED***'),
        (r'Bearer\s+[A-Za-z0-9_-]{20,}', 'Bearer ***REDACTED***'),
        (r'Authorization:\s*[A-Za-z0-9_-]{20,}', 'Authorization: ***REDACTED***'),
        (r'api[_-]?key=[A-Za-z0-9_-]{30,}', 'api_key=***REDACTED***'),
        (r'(?:^|\s)(AIza[A-Za-z0-9_-]{30,})(?:\s|$)', r'\1***REDACTED***'),
        (r'(?:^|\s)(sk-[A-Za-z0-9_-]{30,})(?:\s|$)', r'\1***REDACTED***'),
        (r'(?:^|\s)(gsk-[A-Za-z0-9_-]{30,})(?:\s|$)', r'\1***REDACTED***'),
    ]

    def _redact_string(self, text: str) -> str:
        for pattern, replacement in self.PATTERNS:
            text = re.sub(pattern, replacement, text)
        return text

    def filter(self, record: logging.LogRecord) -> bool:
        if record.args:
            new_args = []
            for arg in record.args:
                if isinstance(arg, str):
                    arg = self._redact_string(arg)
                new_args.append(arg)
            record.args = tuple(new_args)

        if record.msg and isinstance(record.msg, str):
            record.msg = self._redact_string(record.msg)

        return True
