# Generated by Copilot
# Maintained by Dinesh Kumar C (https://github.com/Dinesh210805/blender-mcp)
# Forked from original work by Siddharth Ahuja (https://github.com/ahujasid/blender-mcp)

"""Logging utilities for Blender MCP."""

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

from ..config import config


def setup_logging(
    level: Optional[str] = None,
    log_file: Optional[Path] = None,
    format_string: Optional[str] = None
) -> logging.Logger:
    """Set up logging configuration for Blender MCP."""
    
    # Use config defaults if not provided
    level = level or config.log_level
    format_string = format_string or config.log_format
    
    # Configure root logger
    root_logger = logging.getLogger()
    root_logger.setLevel(getattr(logging, level.upper()))
    
    # Clear existing handlers
    root_logger.handlers.clear()
    
    # Create formatter
    formatter = logging.Formatter(format_string)
    
    # Console handler
    console_handler = logging.StreamHandler(sys.stdout)
    console_handler.setLevel(getattr(logging, level.upper()))
    console_handler.setFormatter(formatter)
    root_logger.addHandler(console_handler)
    
    # File handler (optional)
    if log_file:
        log_file.parent.mkdir(parents=True, exist_ok=True)
        file_handler = logging.FileHandler(log_file)
        file_handler.setLevel(getattr(logging, level.upper()))
        file_handler.setFormatter(formatter)
        root_logger.addHandler(file_handler)
    
    # Create main logger
    logger = logging.getLogger("BlenderMCP")
    
    return logger


def get_logger(name: str) -> logging.Logger:
    """Get a logger with the specified name."""
    return logging.getLogger(f"BlenderMCP.{name}")


def log_tool_call(logger: logging.Logger, tool_name: str, params: dict) -> None:
    """Log tool call with parameters."""
    logger.info(f"Tool call: {tool_name}", extra={
        'tool_name': tool_name,
        'params': params
    })


def log_tool_result(logger: logging.Logger, tool_name: str, success: bool, duration: float) -> None:
    """Log tool result with timing."""
    level = logging.INFO if success else logging.ERROR
    status = "SUCCESS" if success else "FAILED"
    logger.log(level, f"Tool {tool_name} {status} ({duration:.2f}s)", extra={
        'tool_name': tool_name,
        'success': success,
        'duration': duration
    })
