"""Logging configuration utilities."""

import sys
from loguru import logger
from pathlib import Path


def setup_logging(
    log_level: str = "INFO",
    log_format: str = "text",
    log_to_file: bool = True,
    log_dir: str = "logs"
):
    """
    Configure structured logging with loguru.

    Args:
        log_level: Logging level (DEBUG, INFO, WARNING, ERROR)
        log_format: Format type (json or text)
        log_to_file: Whether to log to file
        log_dir: Directory for log files
    """
    # Remove default handler
    logger.remove()

    # Console handler
    if log_format == "json":
        logger.add(
            sys.stdout,
            format="{message}",
            level=log_level,
            serialize=True,
            colorize=False
        )
    else:
        logger.add(
            sys.stdout,
            format="<green>{time:HH:mm:ss}</green> | <level>{level: <8}</level> | <level>{message}</level>",
            level=log_level,
            colorize=True
        )

    # File handler
    if log_to_file:
        log_path = Path(log_dir)
        log_path.mkdir(exist_ok=True)

        if log_format == "json":
            logger.add(
                log_path / "active_call_{time:YYYY-MM-DD}.log",
                format="{message}",
                level=log_level,
                rotation="1 day",
                retention="7 days",
                compression="zip",
                serialize=True
            )
        else:
            logger.add(
                log_path / "active_call_{time:YYYY-MM-DD}.log",
                format="{time:YYYY-MM-DD HH:mm:ss} | {level: <8} | {name}:{function}:{line} - {message}",
                level=log_level,
                rotation="1 day",
                retention="7 days",
                compression="zip"
            )

    return logger


def get_logger(name: str = None):
    """
    Get a logger instance.

    Args:
        name: Logger name (optional)

    Returns:
        Logger instance
    """
    if name:
        return logger.bind(name=name)
    return logger
