"""
Logging configuration using loguru
"""

import sys
from loguru import logger
from typing import Optional

from ..config.settings import get_settings


_logger_configured = False


def setup_logger(
    level: Optional[str] = None,
    format_string: Optional[str] = None,
    serialize: bool = False,
) -> None:
    """
    Setup loguru logger with custom configuration.

    Args:
        level: Log level (DEBUG, INFO, WARNING, ERROR, CRITICAL)
        format_string: Custom format string
        serialize: Whether to serialize logs as JSON
    """
    global _logger_configured

    if _logger_configured:
        return

    settings = get_settings()

    # Remove default handler
    logger.remove()

    # Get configuration
    log_level = level or settings.log_level
    log_format = format_string or settings.log_format

    # Add new handler
    logger.add(
        sys.stderr,
        format=log_format,
        level=log_level,
        serialize=serialize,
        colorize=not serialize,
        backtrace=True,
        diagnose=True,
    )

    _logger_configured = True
    logger.info(f"Logger configured with level: {log_level}")


def get_logger() -> "logger":
    """Get configured logger instance"""
    if not _logger_configured:
        setup_logger()
    return logger


def reset_logger() -> None:
    """Reset logger configuration (useful for testing)"""
    global _logger_configured
    logger.remove()
    _logger_configured = False