"""Logging with secret redaction.

Mirrors community-system/app/core/logging.py. Patterns scrub credentials out
of any log line before the handler sees it. Keep these patterns in sync with
the SECRET_ENV_NAMES listed in app/config.py.
"""

from __future__ import annotations

import logging
import re
import sys


_SECRET_PATTERNS = [
    # query-string style:    ?key=VALUE   &api_key=VALUE   access_token=VALUE
    re.compile(r"(access_token=)[^&\s]+", re.IGNORECASE),
    re.compile(r"(token=)[^&\s]+", re.IGNORECASE),
    re.compile(r"(key=)[^&\s]+", re.IGNORECASE),
    re.compile(r"(api[_-]?key=)[^&\s]+", re.IGNORECASE),
    # Authorization header (Bearer VALUE / Basic VALUE)
    re.compile(r"(Authorization:?\s*)(Bearer\s+)?\S+", re.IGNORECASE),
    # x-api-key: VALUE   (Anthropic's header)
    re.compile(r"(x-api-key:?\s*)\S+", re.IGNORECASE),
    # JSON token keys
    re.compile(r'"token"\s*:\s*"[^"]+"', re.IGNORECASE),
    re.compile(r'"access_token"\s*:\s*"[^"]+"', re.IGNORECASE),
    re.compile(r'"api_key"\s*:\s*"[^"]+"', re.IGNORECASE),
    # Postgres URL inline password:  postgres://user:PASS@host
    re.compile(r"(postgresql(?:\+\w+)?://[^:]+:)[^@]+(@)", re.IGNORECASE),
]


def redact_secrets(value: str) -> str:
    redacted = value
    for pattern in _SECRET_PATTERNS:
        redacted = pattern.sub(
            lambda m: (
                f"{m.group(1)}[REDACTED]"
                if m.lastindex and m.lastindex >= 2 and m.group(2)
                else f"{m.group(0)[:-len(m.group(0)) + len(m.group(1))]}[REDACTED]"
            ),
            redacted,
        )
    return redacted


class SecretRedactingFormatter(logging.Formatter):
    def format(self, record: logging.LogRecord) -> str:
        return redact_secrets(super().format(record))


def setup_logging() -> None:
    handler = logging.StreamHandler(sys.stdout)
    handler.setFormatter(
        SecretRedactingFormatter(
            "%(asctime)s [%(levelname)s] %(name)s: %(message)s"
        )
    )
    root = logging.getLogger()
    root.setLevel(logging.INFO)
    root.handlers.clear()
    root.addHandler(handler)


def get_logger(name: str) -> logging.Logger:
    return logging.getLogger(name)