from __future__ import annotations

import logging
import os
from logging.handlers import RotatingFileHandler
from pathlib import Path

_LOG_FILE_MODE = 0o644


def _prepare_log_file(path: Path) -> None:
    """Crée le fichier de log s'il n'existe pas et fixe ses permissions à 644."""
    path.parent.mkdir(parents=True, exist_ok=True)
    if not path.exists():
        path.touch()
    os.chmod(path, _LOG_FILE_MODE)


def setup_logging(log_file: Path) -> logging.Logger:
    logger = logging.getLogger("securecheck")
    if logger.handlers:
        return logger

    _prepare_log_file(log_file)

    logger.setLevel(logging.INFO)
    logger.propagate = False
    formatter = logging.Formatter(
        fmt="%(asctime)s | %(levelname)s | %(message)s",
        datefmt="%Y-%m-%d %H:%M:%S",
    )

    file_handler = RotatingFileHandler(log_file, maxBytes=1_000_000, backupCount=5, encoding="utf-8")
    file_handler.setFormatter(formatter)
    logger.addHandler(file_handler)
    return logger


def attach_run_handler(logger: logging.Logger, run_log_file: Path) -> RotatingFileHandler:
    _prepare_log_file(run_log_file)

    formatter = logging.Formatter(
        fmt="%(asctime)s | %(levelname)s | %(message)s",
        datefmt="%Y-%m-%d %H:%M:%S",
    )
    handler = RotatingFileHandler(run_log_file, maxBytes=2_000_000, backupCount=2, encoding="utf-8")
    handler.setFormatter(formatter)
    logger.addHandler(handler)
    return handler
