"""Logger setup and configuration."""

import logging
import logging.config
from pathlib import Path
from typing import Optional

import yaml

from src.core.constants import PATHS
from src.core.exceptions import ConfigurationError

# Track if logging has been configured
_logging_configured = False


def get_logger(name: Optional[str] = None) -> logging.Logger:
    """
    Get a logger instance for the given name.

    Args:
        name: Logger name (typically __name__). If None, returns root logger.

    Returns:
        Configured logger instance

    Raises:
        ConfigurationError: If logging configuration cannot be loaded
    """
    global _logging_configured
    
    # Configure logging only once
    if not _logging_configured:
        _configure_logging()
        _logging_configured = True

    # Return logger
    if name:
        return logging.getLogger(name)
    return logging.getLogger()


def _configure_logging() -> None:
    """Configure logging system from YAML file."""
    # Load logging configuration
    logging_config_path = PATHS["config"] / "logging.yaml"
    
    if not logging_config_path.exists():
        raise ConfigurationError(
            f"Logging configuration not found: {logging_config_path}",
            context={"config_path": str(logging_config_path)},
        )

    try:
        with open(logging_config_path, "r") as f:
            config = yaml.safe_load(f)
        
        # Ensure log directories exist
        log_dir = PATHS["logs"]
        log_dir.mkdir(parents=True, exist_ok=True)
        
        # Create subdirectories
        for subdir in ["application", "detectors", "models", "trading", "alerts", "errors", "performance", "audit"]:
            (log_dir / subdir).mkdir(parents=True, exist_ok=True)
        
        # Configure logging
        logging.config.dictConfig(config)
        
    except Exception as e:
        raise ConfigurationError(
            f"Failed to load logging configuration: {e}",
            context={"config_path": str(logging_config_path)},
        ) from e

