import logging
import os
import sys
from logging.handlers import RotatingFileHandler
from pathlib import Path
from typing import override


class MaxLevelFilter(logging.Filter):
    """Filter allowing only log records with level <= max_level."""

    def __init__(self, max_level: int) -> None:
        super().__init__()
        self.max_level: int = max_level

    @override
    def filter(self, record: logging.LogRecord) -> bool:
        return record.levelno <= self.max_level


def _rotating_file_handler(
    filename: Path,
    level: int,
    formatter: logging.Formatter,
    max_bytes: int = 10 * 1024 * 1024,
    backup_count: int = 5,
) -> RotatingFileHandler:
    handler = RotatingFileHandler(
        filename,
        maxBytes=max_bytes,
        backupCount=backup_count,
    )
    handler.setLevel(level)
    handler.setFormatter(formatter)
    return handler


def setup_logging() -> None:
    base_name = __name__.split(".", 1)[0]

    filepath = Path("/var/log/tuxedo-tomte/")
    main_logfile = filepath / "tuxedo-tomte.log"
    startup_logfile = filepath / "tuxedo-tomte-startups.log"
    packages_logfile = filepath / "tuxedo-tomte-packages.log"

    filepath.mkdir(parents=True, exist_ok=True)
    filenames = [packages_logfile, main_logfile, startup_logfile]
    for file in filenames:
        file.touch(exist_ok=True)  # boop

    log_level_str = os.getenv("TUXEDO_TOMTE_LOG_LEVEL", "INFO").upper()
    log_level = getattr(logging, log_level_str, logging.INFO)

    logger = logging.getLogger(base_name)
    logger.setLevel(log_level)
    logger.propagate = False

    if logger.handlers:
        logger.handlers.clear()

    std_formatter = logging.Formatter(
        fmt="{message}",
        style="{",
    )

    main_formatter = logging.Formatter(
        fmt="[{asctime}] {levelname:<8} ({filename}:{lineno} {funcName}): {message}",
        datefmt="%Y-%m-%d %H:%M:%S",
        style="{",
    )

    simple_formatter = logging.Formatter(
        fmt="[{asctime}] {message}",
        datefmt="%Y-%m-%d %H:%M:%S",
        style="{",
    )

    # -------------------------
    # STDOUT-Handler: DEBUG + INFO
    # -------------------------
    stdout_handler = logging.StreamHandler(sys.stdout)
    stdout_handler.setLevel(logging.DEBUG)
    stdout_handler.addFilter(MaxLevelFilter(logging.INFO))  # bis INFO
    stdout_handler.setFormatter(std_formatter)

    # -------------------------
    # STDERR-Handler: WARNING, ERROR, CRITICAL
    # -------------------------
    stderr_handler = logging.StreamHandler(sys.stderr)
    stderr_handler.setLevel(logging.WARNING)
    stderr_handler.setFormatter(std_formatter)

    # -------------------------
    # rotating-Handler: WARNING, ERROR, CRITICAL, DEBUG, INFO
    # -------------------------

    main_file = _rotating_file_handler(
        filename=main_logfile,
        level=logging.DEBUG,
        formatter=main_formatter,
    )

    logger.addHandler(stdout_handler)
    logger.addHandler(stderr_handler)
    logger.addHandler(main_file)

    # -------------------------
    # Startup logger: rotating file only (no filters, no extra handlers)
    # -------------------------
    startup_logger = logging.getLogger(f"{base_name}.startup")
    startup_logger.setLevel(logging.INFO)
    startup_logger.propagate = False

    startup_file = _rotating_file_handler(
        filename=startup_logfile,
        level=logging.INFO,
        formatter=simple_formatter,
    )
    startup_logger.addHandler(startup_file)

    # -------------------------
    # Packages logger: rotating file only (no filters, no extra handlers)
    # -------------------------
    packages_logger = logging.getLogger(f"{base_name}.packages")
    packages_logger.setLevel(logging.DEBUG)
    packages_logger.propagate = False

    packages_file = _rotating_file_handler(
        filename=packages_logfile,
        level=logging.DEBUG,
        formatter=simple_formatter,
    )
    packages_logger.addHandler(packages_file)
