"""
logging.py
-----------
Structured, unified logging configuration for the HIEROMEM API.

This setup standardizes logging across:
  • FastAPI / Uvicorn server logs
  • HIEROMEM core and persistence backends
  • Custom application events

Supports both console and file logging.
Integrates cleanly with Prometheus, Docker, and OpenTelemetry.

Author: Sai Rishi Kiran Mannava
"""

from __future__ import annotations
import logging
import sys
from pathlib import Path
from typing import Optional


# --------------------------------------------------------------------------- #
# Color support (optional)
# --------------------------------------------------------------------------- #

class _ColorFormatter(logging.Formatter):
    """Adds basic color highlighting for log levels in console."""

    COLORS = {
        "DEBUG": "\033[37m",     # white
        "INFO": "\033[36m",      # cyan
        "WARNING": "\033[33m",   # yellow
        "ERROR": "\033[31m",     # red
        "CRITICAL": "\033[41m",  # red background
    }
    RESET = "\033[0m"

    def format(self, record: logging.LogRecord) -> str:
        color = self.COLORS.get(record.levelname, "")
        levelname = f"{color}{record.levelname}{self.RESET}"
        record.levelname = levelname
        return super().format(record)


# --------------------------------------------------------------------------- #
# Logging Setup
# --------------------------------------------------------------------------- #

def setup_logging(
    level: str = "INFO",
    log_file: Optional[str | Path] = None,
    include_uvicorn: bool = True,
) -> None:
    """
    Initialize structured logging.

    Args:
        level (str): Log level (DEBUG, INFO, WARNING, ERROR)
        log_file (Optional[str | Path]): Optional file path for persistent logs
        include_uvicorn (bool): Whether to unify Uvicorn/FastAPI logs

    Example:
        setup_logging(level="DEBUG", log_file="logs/hieromem.log")
    """
    log_level = getattr(logging, level.upper(), logging.INFO)

    # Console handler with colors
    console_handler = logging.StreamHandler(sys.stdout)
    console_handler.setFormatter(
        _ColorFormatter("[%(asctime)s] [%(levelname)s] %(name)s: %(message)s")
    )

    handlers: list[logging.Handler] = [console_handler]

    # Optional file handler
    if log_file:
        log_path = Path(log_file)
        log_path.parent.mkdir(parents=True, exist_ok=True)
        file_handler = logging.FileHandler(log_path, encoding="utf-8")
        file_handler.setFormatter(logging.Formatter(
            "[%(asctime)s] [%(levelname)s] %(name)s: %(message)s"))
        handlers.append(file_handler)

    # Root logger
    logging.basicConfig(level=log_level, handlers=handlers)

    # Quiet down dependency libraries
    if include_uvicorn:
        logging.getLogger("uvicorn").setLevel(logging.WARNING)
        logging.getLogger("uvicorn.error").setLevel(logging.WARNING)
        logging.getLogger("uvicorn.access").setLevel(logging.WARNING)
        logging.getLogger("fastapi").setLevel(logging.WARNING)
    logging.getLogger("asyncio").setLevel(logging.WARNING)
    logging.getLogger("httpx").setLevel(logging.WARNING)
    logging.getLogger("urllib3").setLevel(logging.WARNING)

    # Confirm setup
    logging.getLogger("hieromem_api").info(
        f"[logging] Initialized at level={level.upper()}, log_file={'on' if log_file else 'off'}"
    )


# --------------------------------------------------------------------------- #
# Utility logger helper
# --------------------------------------------------------------------------- #

def get_logger(name: str) -> logging.Logger:
    """
    Convenience wrapper for module-level loggers.

    Example:
        logger = get_logger(__name__)
        logger.info("Something happened")
    """
    return logging.getLogger(name)
