"""Centralized logging configuration for Reviewate

This module provides structured logging for container-based execution.
The backend listens to these logs to track workflow status.

Log Levels:
- INFO: Workflow status updates, important milestones
- WARNING: Recoverable errors, partial failures
- ERROR: Fatal errors that stop execution
- DEBUG: Detailed debugging information (not shown in container)
"""

import logging
import os
import sys
from typing import Any

# Disable LiteLLM verbose logging before it initializes
os.environ["LITELLM_LOG"] = "ERROR"

# Suppress LiteLLM "Give Feedback / Get Help" stdout prints (bypass logging)
try:
    import litellm

    litellm.suppress_debug_info = True
except ImportError:
    pass


def setup_logging(level: str = "INFO", debug: bool = False) -> None:
    """Configure logging for the application

    Args:
        level: Log level (DEBUG, INFO, WARNING, ERROR)
        debug: If True, enable DEBUG level for verbose output
    """
    # Normal mode: use provided level (INFO by default for progress logs)
    # Debug mode: use DEBUG for verbose output
    effective_level = "DEBUG" if debug else level.upper()

    # Create root logger
    root_logger = logging.getLogger()
    root_logger.setLevel(getattr(logging, effective_level))

    # Remove any existing handlers
    root_logger.handlers.clear()

    # Create console handler with custom format
    console_handler = logging.StreamHandler(sys.stdout)
    console_handler.setLevel(getattr(logging, effective_level))

    # Custom format for container logs
    # Format: [TIMESTAMP] [LEVEL] [MODULE] MESSAGE
    formatter = logging.Formatter(
        fmt="[%(asctime)s] [%(levelname)-8s] [%(name)s] %(message)s",
        datefmt="%Y-%m-%d %H:%M:%S",
    )
    console_handler.setFormatter(formatter)

    # Add handler to root logger
    root_logger.addHandler(console_handler)

    # Silence noisy third-party loggers
    logging.getLogger("httpx").setLevel(logging.WARNING)
    logging.getLogger("httpcore").setLevel(logging.WARNING)
    logging.getLogger("httpcore.connection").setLevel(logging.WARNING)
    logging.getLogger("httpcore.http11").setLevel(logging.WARNING)

    # Completely silence LiteLLM (very verbose)
    logging.getLogger("LiteLLM").setLevel(logging.ERROR)
    logging.getLogger("litellm").setLevel(logging.ERROR)
    logging.getLogger("LiteLLM Proxy").setLevel(logging.ERROR)

    # Disable LiteLLM's own loggers completely
    litellm_logger = logging.getLogger("LiteLLM")
    litellm_logger.handlers = []
    litellm_logger.propagate = False


class BaseLogger:
    """Base logger wrapper that adds a structured component prefix to messages.

    Use this as a lightweight wrapper around the standard logging.Logger so
    every usage has a consistent, parseable prefix. Specialized loggers
    (WorkflowLogger, AgentLogger, PlatformLogger) extend this.
    """

    def __init__(self, component_type: str, component_name: str):
        """Create a BaseLogger.

        Args:
            component_type: Logical component type (workflow/agent/platform/app)
            component_name: Name of the component instance
        """
        self.component_type = component_type
        self.component_name = component_name
        self.logger = logging.getLogger(f"{component_type}.{component_name}")

    def _prefix(self) -> str:
        return f"{self.component_type}={self.component_name}"

    def info(self, msg: str, **fields: Any) -> None:
        suffix = " " + " ".join(f"{k}={v}" for k, v in fields.items()) if fields else ""
        self.logger.info(f"{self._prefix()} {msg}{suffix}")

    def debug(self, msg: str, **fields: Any) -> None:
        suffix = " " + " ".join(f"{k}={v}" for k, v in fields.items()) if fields else ""
        self.logger.debug(f"{self._prefix()} {msg}{suffix}")

    def warning(self, msg: str, **fields: Any) -> None:
        suffix = " " + " ".join(f"{k}={v}" for k, v in fields.items()) if fields else ""
        self.logger.warning(f"{self._prefix()} {msg}{suffix}")

    def error(self, msg: str, **fields: Any) -> None:
        suffix = " " + " ".join(f"{k}={v}" for k, v in fields.items()) if fields else ""
        self.logger.error(f"{self._prefix()} {msg}{suffix}")

    def exception(self, msg: str, **fields: Any) -> None:
        """Log an exception with traceback (delegates to logger.exception)."""
        suffix = " " + " ".join(f"{k}={v}" for k, v in fields.items()) if fields else ""
        self.logger.exception(f"{self._prefix()} {msg}{suffix}")
