import os
import sys

from loguru import logger


def setup_logger(log_level=None):
    """Configure loguru logger with appropriate settings.

    Args:
        log_level: Logging level string (DEBUG, INFO, WARNING, ERROR, CRITICAL).
                   If None, reads from LOG_LEVEL env var, defaulting to INFO.

    Returns:
        Configured logger instance
    """
    if log_level is None:
        log_level = os.environ.get("LOG_LEVEL", "INFO").upper()
    else:
        log_level = log_level.upper()

    # Remove all existing handlers before reconfiguring
    logger.remove()

    # Add console handler with colored output
    logger.add(
        sys.stderr,
        format="<green>{time:YYYY-MM-DD HH:mm:ss}</green> | <level>{level: <8}</level> | "
        "<cyan>{name}</cyan>:<cyan>{function}</cyan>:<cyan>{line}</cyan> - <level>{message}</level>",
        level=log_level,
        colorize=True,
    )

    # Add file handler for errors and critical logs
    os.makedirs("logs", exist_ok=True)
    logger.add(
        "logs/errors.log",
        format="{time:YYYY-MM-DD HH:mm:ss} | {level: <8} | {name}:{function}:{line} - {message}",
        level="ERROR",
        rotation="10 MB",
        retention="1 week",
        backtrace=True,
        diagnose=False,
    )

    # Add file handler for all logs
    logger.add(
        "logs/all.log",
        format="{time:YYYY-MM-DD HH:mm:ss} | {level: <8} | {name}:{function}:{line} - {message}",
        level=log_level,
        rotation="10 MB",
        retention="1 week",
    )

    return logger


# Initialize with default settings; main() reconfigures with resolved config
logger = setup_logger()  # noqa: F811
