import os
import sys

from loguru import logger


def configure_logging() -> None:
    """Configure Loguru logging with JSON format for Alloy/Loki collection.

    Following ADR 0003 specifications with enhanced observability features:
    - JSON structured logging for Grafana Loki ingestion
    - Automatic trace context integration via contextualize() in tracing module
    - Container-friendly stdout output for Alloy collection
    """
    # Remove default handler
    logger.remove()

    # JSON handler for Alloy collection (stdout for container logs)
    # Use Loguru's built-in serialize=True for proper JSON formatting
    logger.add(
        sys.stdout,
        serialize=True,  # Built-in JSON serialization creates proper structure
        level="INFO",
        enqueue=True,  # Thread-safe logging
        backtrace=True,  # Include full tracebacks
        diagnose=True,  # Variable values in exceptions
    )

    # Development console handler (human-readable format)
    environment = os.getenv("ENVIRONMENT", "development")
    if environment == "development":
        logger.add(
            sys.stderr,
            format="<green>{time:YYYY-MM-DD HH:mm:ss.SSS}</green> | "
            "<level>{level: <8}</level> | "
            "<cyan>{name}:{function}:{line}</cyan> | "
            "<level>{message}</level>",
            level="DEBUG",
            colorize=True,
            enqueue=True,
            backtrace=True,
            diagnose=True,
        )

    logger.info(
        "Logging configured for Alloy collection with trace context integration"
    )


# Export configured logger
__all__ = ["logger", "configure_logging"]
