import logging
from typing import Self

from snakestack.logging.contexts import get_request_id


class RequestIdFilter(logging.Filter):
    def filter(self: Self, record: logging.LogRecord) -> bool:
        record.request_id = get_request_id()
        return True

class ExcludeLoggerFilter(logging.Filter):
    def __init__(self: Self, excluded_name: list[str]) -> None:
        super().__init__()
        cleaned = [n.strip() for n in excluded_name if n and n.strip()]
        self.excluded = tuple(sorted(set(cleaned)))

    def filter(self: Self, record: logging.LogRecord) -> bool:
        name = record.name
        return not any(name == n or name.startswith(f"{n}." ) for n in self.excluded)


class PathFilter(logging.Filter):
    def __init__(self: Self, paths: list[str] | None) -> None:
        super().__init__()
        self.paths = paths or []

    def filter(self: Self, record: logging.LogRecord) -> bool:
        if hasattr(record, "path_url"):
            url = record.path_url
            return not any(url.startswith(path) for path in self.paths)

        return True
