"""
Logging framework — rotating file log + console.
"""

import os
import logging
import logging.handlers

SHARED_DIR = os.path.expanduser("~/.server-connections")
LOG_FILE = os.path.join(SHARED_DIR, "app.log")


def get_logger(name: str = "servermanager") -> logging.Logger:
    """Get or create a named logger with file + console handlers."""
    logger = logging.getLogger(name)
    if logger.handlers:
        return logger

    logger.setLevel(logging.DEBUG)

    # File handler — rotating, 5MB max, 3 backups
    os.makedirs(SHARED_DIR, exist_ok=True)
    fh = logging.handlers.RotatingFileHandler(
        LOG_FILE, maxBytes=5 * 1024 * 1024, backupCount=3, encoding="utf-8"
    )
    fh.setLevel(logging.DEBUG)
    fh.setFormatter(logging.Formatter(
        "%(asctime)s [%(levelname)s] %(name)s: %(message)s",
        datefmt="%Y-%m-%d %H:%M:%S"
    ))
    logger.addHandler(fh)

    return logger


log = get_logger()
