"""Logging utilities for MCP context-aware logging.

Provides async logging functions that use FastMCP's Context for
client-visible logging when available, with fallback to standard logging.
"""

import logging
from typing import TYPE_CHECKING, Optional

if TYPE_CHECKING:
    from fastmcp import Context

# Standard Python logger as fallback
logger = logging.getLogger("mcghidra")


async def log_debug(ctx: Optional["Context"], message: str) -> None:
    """Log a debug message to the MCP client and/or standard logger.

    Args:
        ctx: FastMCP context (may be None)
        message: Debug message to log
    """
    logger.debug(message)
    if ctx is not None:
        try:
            await ctx.debug(message)
        except Exception:
            pass  # Silently ignore if context doesn't support logging


async def log_info(ctx: Optional["Context"], message: str) -> None:
    """Log an info message to the MCP client and/or standard logger.

    Args:
        ctx: FastMCP context (may be None)
        message: Info message to log
    """
    logger.info(message)
    if ctx is not None:
        try:
            await ctx.info(message)
        except Exception:
            pass


async def log_warning(ctx: Optional["Context"], message: str) -> None:
    """Log a warning message to the MCP client and/or standard logger.

    Args:
        ctx: FastMCP context (may be None)
        message: Warning message to log
    """
    logger.warning(message)
    if ctx is not None:
        try:
            await ctx.warning(message)
        except Exception:
            pass


async def log_error(ctx: Optional["Context"], message: str) -> None:
    """Log an error message to the MCP client and/or standard logger.

    Args:
        ctx: FastMCP context (may be None)
        message: Error message to log
    """
    logger.error(message)
    if ctx is not None:
        try:
            await ctx.error(message)
        except Exception:
            pass


def configure_logging(level: int = logging.INFO) -> None:
    """Configure the standard logger for MCGhidra.

    Args:
        level: Logging level (default: INFO)
    """
    handler = logging.StreamHandler()
    handler.setFormatter(
        logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
    )
    logger.addHandler(handler)
    logger.setLevel(level)
