"""
OmniSec Core Logger
Structured logging with color support and rotating file handler.
"""

import logging
import sys
from logging.handlers import RotatingFileHandler
from typing import Optional
import os

LOG_COLORS = {
    "DEBUG":    "\033[36m",
    "INFO":     "\033[32m",
    "WARNING":  "\033[33m",
    "ERROR":    "\033[31m",
    "CRITICAL": "\033[41m",
    "RESET":    "\033[0m",
}


class ColorFormatter(logging.Formatter):
    """Formatter that injects ANSI color codes based on log level."""

    def format(self, record):
        color = LOG_COLORS.get(record.levelname, LOG_COLORS["RESET"])
        reset = LOG_COLORS["RESET"]
        record.levelname = f"{color}{record.levelname:<8}{reset}"
        return super().format(record)


def get_logger(
    name: str = "omnisec",
    level: str = "INFO",
    log_file: Optional[str] = None,
    max_bytes: int = 10_000_000,
    backup_count: int = 5,
) -> logging.Logger:
    """
    Get a configured OmniSec logger.

    Args:
        name:         Logger name (default: 'omnisec')
        level:        Log level string — DEBUG | INFO | WARNING | ERROR | CRITICAL
        log_file:     Optional path for rotating file logs
        max_bytes:    Max file size before rotation (default 10 MB)
        backup_count: Backup log file count

    Returns:
        Configured logging.Logger instance

    Example:
        >>> log = get_logger("omnisec.security", level="DEBUG")
        >>> log.info("SecurityToolkit initialized")
    """
    logger = logging.getLogger(name)
    if logger.handlers:
        return logger

    logger.setLevel(getattr(logging, level.upper(), logging.INFO))
    fmt = "%(asctime)s | %(name)-25s | %(levelname)s | %(message)s"
    datefmt = "%Y-%m-%d %H:%M:%S"

    console = logging.StreamHandler(sys.stdout)
    console.setFormatter(ColorFormatter(fmt, datefmt=datefmt))
    logger.addHandler(console)

    if log_file:
        os.makedirs(os.path.dirname(os.path.abspath(log_file)), exist_ok=True)
        fh = RotatingFileHandler(log_file, maxBytes=max_bytes, backupCount=backup_count)
        fh.setFormatter(logging.Formatter(fmt, datefmt=datefmt))
        logger.addHandler(fh)

    return logger
