"""Structured logging configuration using loguru.

Configure the global loguru logger with structured output.
Other modules can simply: from loguru import logger

Usage:
    from loguru import logger
    logger.info('message', key1=value1, key2=value2)
"""

import sys

from loguru import logger

# Remove default handler
logger.remove()

# Custom format function for structured logging
def _format(record: "loguru._logger.Record") -> str:
    """Format log record with structured fields as key=value."""
    # Get caller info
    file_path = record["file"].name
    short_file = file_path.split("/")[-1] if "/" in file_path else file_path
    line = record["line"]
    func = record["function"]

    # Build message
    message = record["message"]

    # Format extra fields as key=value
    extra = record.get("extra", {})
    parts = []
    for key, value in extra.items():
        if isinstance(value, str) and (" " in value or "=" in value):
            parts.append(f'{key}="{value}"')
        elif value is None:
            parts.append(f"{key}=null")
        elif isinstance(value, bool):
            parts.append(f"{key}={'true' if value else 'false'}")
        else:
            parts.append(f"{key}={value}")

    fields_str = f" {' '.join(parts)}" if parts else ""

    # Write directly to stdout to bypass loguru's colorizer
    sys.stdout.write(f"[{short_file}:{line} {func}] {message}{fields_str}\n")
    sys.stdout.flush()

    # Return empty string to suppress loguru's own output
    return ""


# Add configured handler with our custom format
logger.add(
    sys.stdout,
    format=_format,
    level="INFO",
    colorize=False,
)
