"""AbletonMCP_AI Engines Package - Architecture Integration Module.

This module wires together all the engines and provides a unified interface
for the MCP server to access music production capabilities.

Architecture Overview:
======================

┌─────────────────────────────────────────────────────────────────────────────┐
│                         ENGINES PACKAGE                                     │
├─────────────────────────────────────────────────────────────────────────────┤
│                                                                             │
│  ┌─────────────────┐  ┌─────────────────┐  ┌─────────────────┐               │
│  │  Metadata &     │  │  Arrangement    │  │  Live Bridge    │               │
│  │  Analysis       │  │  Recording      │  │                 │               │
│  │                 │  │                 │  │                 │               │
│  │ • metadata_     │  │ • arrangement_  │  │ • live_bridge   │               │
│  │   store         │  │   recorder      │  │                 │               │
│  │ • abstract_     │  │                 │  │   (Connection   │               │
│  │   analyzer      │  │                 │  │    management)  │               │
│  │                 │  │                 │  │                 │               │
│  └────────┬────────┘  └────────┬────────┘  └────────┬────────┘               │
│           │                    │                    │                        │
│           └────────────────────┼────────────────────┘                        │
│                                ▼                                             │
│  ┌─────────────────────────────────────────────────────────────────────┐    │
│  │           SENIOR ARCHITECTURE - INTELLIGENT SELECTION               │    │
│  │                                                                     │    │
│  │  • intelligent_selector   - Coherent kit selection with validation  │    │
│  │  • coherence_scorer       - Spectral coherence quality scoring       │    │
│  │  • variation_engine       - Section-based kit evolution              │    │
│  │  • rationale_logger       - Selection decision logging               │    │
│  │  • preset_manager         - Kit preset save/load                     │    │
│  │  • iteration_engine       - Auto-iteration to professional grade     │    │
│  │                                                                     │    │
│  └─────────────────────────────────────────────────────────────────────┘    │
│                                ▼                                             │
│  ┌─────────────────────────────────────────────────────────────────────┐    │
│  │                    EXISTING ENGINES (Sprints 1-3)                    │    │
│  │                                                                     │    │
│  │  Sprint 1: Core Analysis        Sprint 2: Pattern & Mixing          │    │
│  │  • libreria_analyzer              • pattern_library                 │    │
│  │  • embedding_engine               • song_generator                  │    │
│  │  • reference_matcher              • mixing_engine                   │    │
│  │  • sample_selector                • workflow_engine                 │    │
│  │                                                                     │    │
│  │  Sprint 3: Arrangement & Harmony                                  │    │
│  │  • arrangement_engine               • harmony_engine                │    │
│  │  • preset_system                    • production_workflow         │    │
│  │  • musical_intelligence                                             │    │
│  │                                                                     │    │
│  └─────────────────────────────────────────────────────────────────────┘    │
│                                                                             │
│  Key Design Principles:                                                    │
│  ───────────────────────                                                     │
│  • Lazy loading: All numpy/librosa-dependent modules load only when used   │
│  • Graceful degradation: Missing dependencies don't break the system     │
│  • Singleton pattern: Shared state via init_*() functions                  │
│  • Compatibility layer: Maintains backward compatibility                   │
│                                                                             │
└─────────────────────────────────────────────────────────────────────────────┘

Usage:
======

    # Quick initialization
    from AbletonMCP_AI.mcp_server.engines import (
        init_metadata_store,
        init_arrangement_recorder,
        init_live_bridge,
        get_analyzer,
    )
    
    # Initialize systems
    store = init_metadata_store()
    analyzer = get_analyzer(prefer_database=True)
    recorder = init_arrangement_recorder(song, connection)
    bridge = init_live_bridge(song, connection)
    
    # Initialize Intelligent Selection System
    from AbletonMCP_AI.mcp_server.engines import (
        init_intelligent_selector,
        init_coherence_scorer,
        init_variation_engine,
        init_rationale_logger,
        init_preset_manager,
        init_iteration_engine,
    )
    
    scorer = init_coherence_scorer()
    selector = init_intelligent_selector(coherence_scorer=scorer)
    variation = init_variation_engine()
    rationale = init_rationale_logger(session_id="session_001")
    presets = init_preset_manager()
    iterator = init_iteration_engine(intelligent_selector=selector, max_iterations=10)
    
    # Use existing engines (backward compatible)
    from AbletonMCP_AI.mcp_server.engines import (
        SampleSelector, EmbeddingEngine, ReggaetonGenerator,
        MixingEngine, ArrangementBuilder
    )

Capabilities Detection:
=======================

The system auto-detects available capabilities:

    - numpy: Required for numerical analysis
    - librosa: Required for audio feature extraction
    - sqlite3: Required for metadata database
    - python_version: For compatibility checks

Engines gracefully degrade when dependencies are missing.

Version: 1.0.0
"""

from __future__ import annotations

import sys
import logging
from typing import TYPE_CHECKING, Optional, Dict, Any
from enum import Enum

# Configure logging for the engines package
logger = logging.getLogger(__name__)

# =============================================================================
# LAZY IMPORT SYSTEM
# =============================================================================
# This allows the module to be imported even when optional dependencies
# (numpy, librosa) are not available. The heavy modules are only loaded
# when their functionality is actually accessed.

class LazyModule:
    """Lazy module loader that imports only when accessed."""
    
    def __init__(self, name: str, import_path: str, fallback=None):
        self.name = name
        self.import_path = import_path
        self._module = None
        self._fallback = fallback
        self._error = None
    
    def _import(self):
        if self._module is None and self._error is None:
            try:
                parts = self.import_path.split('.')
                module = __import__(self.import_path, fromlist=[parts[-1]])
                self._module = module
                logger.debug(f"Lazy loaded module: {self.import_path}")
            except ImportError as e:
                self._error = e
                logger.warning(f"Could not import {self.import_path}: {e}")
                if self._fallback:
                    self._module = self._fallback
        return self._module
    
    def __getattr__(self, name: str):
        module = self._import()
        if module is None:
            raise ImportError(
                f"Module {self.import_path} not available. "
                f"Original error: {self._error}"
            )
        return getattr(module, name)
    
    def __call__(self, *args, **kwargs):
        # If this represents a class/function, allow calling
        callable_ = self._import()
        if callable_ is None:
            raise ImportError(
                f"Module {self.import_path} not available. "
                f"Original error: {self._error}"
            )
        return callable_(*args, **kwargs)
    
    def is_available(self) -> bool:
        """Check if the lazy-loaded module is available."""
        return self._import() is not None


# =============================================================================
# MODULE AVAILABILITY TRACKING
# =============================================================================

class ModuleAvailability(Enum):
    """Tracks which modules are available."""
    AVAILABLE = "available"
    MISSING = "missing"
    DEGRADED = "degraded"  # Available but with limited functionality


# Global registry of module availability
_module_availability: Dict[str, ModuleAvailability] = {}

def _mark_available(name: str, status: ModuleAvailability = ModuleAvailability.AVAILABLE):
    """Mark a module as available."""
    _module_availability[name] = status

def _mark_missing(name: str):
    """Mark a module as missing."""
    _module_availability[name] = ModuleAvailability.MISSING

def is_module_available(name: str) -> bool:
    """Check if a module is available."""
    return _module_availability.get(name) == ModuleAvailability.AVAILABLE


# =============================================================================
# EXISTING ENGINES (Sprints 1-3) - Always Available
# =============================================================================

# Sprint 1: Core Analysis
from .libreria_analyzer import LibreriaAnalyzer, analyze_library
_mark_available("libreria_analyzer")

from .embedding_engine import (
    EmbeddingEngine, 
    create_embeddings_index, 
    find_similar_samples, 
    find_samples_like_audio
)
_mark_available("embedding_engine")

from .reference_matcher import (
    ReferenceMatcher, SpectralFingerprint, SampleMatch, UserSoundProfile,
    AudioAnalyzer, SimilarityEngine, get_matcher, get_user_profile,
    get_recommended_samples, analyze_reference, refresh_profile,
)
_mark_available("reference_matcher")

from .sample_selector import (
    SampleSelector, SampleInfo, DrumKit, InstrumentGroup,
    get_selector, select_samples_for_track, get_drum_kit, reset_cross_generation_memory,
)
_mark_available("sample_selector")

# Sprint 2: Pattern & Mixing
# Sprint 7: Added ChordProgressionsPro (16 progresiones con tensión, acordes extendidos, inversiones)
from .pattern_library import (
    DembowPatterns, BassPatterns, ChordProgressions, ChordProgressionsPro,
    MelodyGenerator, HumanFeel, PercussionLibrary, NoteEvent, ScaleType,
    get_patterns,
)
_mark_available("pattern_library")

# Agente 15: Reggaeton Rhythm Patterns Library
from .reggaeton_patterns import (
    ReggaetonPatterns, RhythmicEvent, PatternType, get_rhythmic_pattern,
)
_mark_available("reggaeton_patterns")

from .song_generator import (
    ReggaetonGenerator, SongGenerator, SongConfig, Section, TrackConfig,
    ClipConfig, Pattern, DeviceConfig, get_song_generator, generate_song,
    generate_from_reference, get_supported_styles, get_supported_structures,
)
_mark_available("song_generator")

from .mixing_engine import (
    MixingEngine, BusManager, ReturnTrackManager, MixConfiguration,
    get_mixing_engine, reset_mixing_engine, DeviceManager, EQConfiguration,
    CompressionSettings, GainStaging, MasterChain, DeviceParameter,
    MixQualityChecker, DeviceInfo, QualityReport, SUPPORTED_DEVICES,
    EQ_PRESETS, COMP_PRESETS, MASTER_PRESETS, get_device_manager,
    get_eq_configuration, get_compression_settings, get_gain_staging,
    get_master_chain, get_device_parameter, get_quality_checker,
    create_standard_buses, apply_send_preset,
)
_mark_available("mixing_engine")

# Real-time Gain Staging with Metering (Agente 11)
try:
    from .gain_staging import (
        GainStaging as GainStagingMeter,
        TrackLevelInfo, MasterLevelInfo, ProjectLevelAnalysis,
        LevelAlert, analyze_levels,
        get_gain_staging as get_gain_staging_meter,
        reset_gain_staging,
    )
    _mark_available("gain_staging")
except ImportError as e:
    _mark_missing("gain_staging")
    logger.debug(f"gain_staging not available: {e}")

from .workflow_engine import (
    ProductionWorkflow, ActionHistory, ProjectValidator, ExportManager,
    ActionRecord, ValidationIssue, get_workflow,
)
_mark_available("workflow_engine")

# Agente 6: Curve Interpolation (Automation Curves)
try:
    from .curve_interpolation import (
        linear_interpolation,
        bezier_interpolation,
        s_curve_interpolation,
        exponential_interpolation,
        stepped_interpolation,
        generate_curve,
        create_filter_sweep,
        create_volume_fade,
        create_send_automation,
        CurveConfig,
        CurveType,
        AutomationPoint,
        GridQuantization,
        quantize_time,
        quantize_points,
        GRID_QUARTER,
        GRID_EIGHTH,
        GRID_SIXTEENTH,
        GRID_THIRTYSECOND,
    )
    _mark_available("curve_interpolation")
except ImportError as e:
    _mark_missing("curve_interpolation")
    logger.debug(f"curve_interpolation not available: {e}")

# Sprint 3: Arrangement & Harmony
from .arrangement_engine import (
    ArrangementBuilder, AutomationEngine, FXCreator, SampleProcessor,
    ArrangementConfig, SectionMarker, AutomationPoint, AutomationEnvelope,
    ArrangementClip, ArrangementSection, arrangement_to_dict, dict_to_arrangement,
    get_arrangement_length, create_full_arrangement,
)
_mark_available("arrangement_engine")

from .harmony_engine import (
    ProjectAnalyzer, CounterMelodyGenerator, VariationEngine, SampleIntelligence,
)
_mark_available("harmony_engine")

from .preset_system import (
    PresetManager, Preset, TrackPreset, MixingConfig, SampleSelectionCriteria,
    get_preset_manager, apply_preset_to_project, get_default_preset,
    list_available_presets, quick_apply_preset, create_builtin_presets,
)
_mark_available("preset_system")

# Sprint 4: Iteration & Quality Assurance
from .iteration_engine import (
    IterationEngine, ProfessionalCoherenceError,
    CoherenceScorer, RationaleLogger,
    IterationResult, IterationAttempt, IterationStatus,
    ITERATION_STRATEGIES,
    iterate_for_coherence, quick_coherence_check,
)
_mark_available("iteration_engine")

# Agente 16: Pad and Texture Layer System
from .texture_engine import (
    TextureEngine, PadLayer, TextureConfiguration, AutomationPoint,
    PadType, SyncopationPattern, ArpeggioPattern,
    create_texture_engine, generate_quick_pad, get_texture_engine,
)
_mark_available("texture_engine")

# Agente 18+: Ambience Generator for intros/outros
from .ambience_generator import (
    AmbienceGenerator, AmbienceLayer, AmbienceConfiguration,
    create_intro_ambience, create_outro_fade, inject_ambience_to_track,
)
_mark_available("ambience_generator")

# Optional engines that might not exist in all installations
optional_engines = [
    ("musical_intelligence", "MusicalIntelligence, PhraseAnalyzer, MotifLibrary"),
    ("production_workflow", "ProductionOrchestrator"),
    ("noise_generator", "WhiteNoiseGenerator, get_noise_generator"),
    ("midi_orchestrator", "MIDIOrchestrator, MIDIFileInfo, MIDIType, MIDISource, create_orchestrator, get_midi_catalog, categorize_library"),
]

for engine_name, exports in optional_engines:
    try:
        exec(f"from .{engine_name} import {exports}")
        _mark_available(engine_name)
    except ImportError:
        _mark_missing(engine_name)
        logger.debug(f"Optional engine {engine_name} not available")

# Section Sample Mapper - Maps samples to song sections
try:
    from .section_sample_mapper import (
        SectionSampleMapper, SectionMapping, create_section_mapper,
    )
    _mark_available("section_sample_mapper")
except ImportError as e:
    _mark_missing("section_sample_mapper")
    logger.debug(f"section_sample_mapper not available: {e}")
    
    class SectionSampleMapper:
        """Placeholder - section_sample_mapper module not available."""
        def __init__(self, *args, **kwargs):
            raise ImportError("section_sample_mapper module not available")
    
    class SectionMapping:
        """Placeholder - section_sample_mapper module not available."""
        pass
    
    def create_section_mapper(*args, **kwargs):
        raise ImportError("section_sample_mapper module not available")


# =============================================================================
# NEW COMPONENTS (With Graceful Fallback)
# =============================================================================

# Metadata and Analysis
_metadata_store_loaded = False
try:
    from .metadata_store import SampleMetadataStore, SampleFeatures
    _metadata_store_loaded = True
    _mark_available("metadata_store")
except ImportError as e:
    _mark_missing("metadata_store")
    logger.debug(f"metadata_store not available: {e}")
    # Define placeholder classes
    class SampleMetadataStore:
        """Placeholder - metadata_store module not available."""
        def __init__(self, *args, **kwargs):
            raise ImportError("metadata_store module not available")
    
    class SampleFeatures:
        """Placeholder - metadata_store module not available."""
        pass

# Abstract Analyzer - uses lazy loading for librosa-dependent components
_abstract_analyzer_loaded = False
try:
    from .abstract_analyzer import (
        FeatureExtractor, LibrosaExtractor, 
        DatabaseExtractor, HybridExtractor
    )
    _abstract_analyzer_loaded = True
    _mark_available("abstract_analyzer")
except ImportError as e:
    _mark_missing("abstract_analyzer")
    logger.debug(f"abstract_analyzer not available: {e}")
    
    # Define placeholder base classes
    class FeatureExtractor:
        """Placeholder base class for feature extraction."""
        def extract(self, sample_path: str) -> Dict[str, Any]:
            raise NotImplementedError("FeatureExtractor not available")
    
    class LibrosaExtractor(FeatureExtractor):
        """Placeholder - librosa-based extraction not available."""
        def __init__(self, *args, **kwargs):
            raise ImportError("LibrosaExtractor requires librosa and numpy")
    
    class DatabaseExtractor(FeatureExtractor):
        """Placeholder - database extraction not available."""
        def __init__(self, *args, **kwargs):
            raise ImportError("DatabaseExtractor requires metadata_store")
    
    class HybridExtractor(FeatureExtractor):
        """Placeholder - hybrid extraction not available."""
        def __init__(self, *args, **kwargs):
            raise ImportError("HybridExtractor requires abstract_analyzer module")

# Arrangement Recording
_arrangement_recorder_loaded = False
try:
    from .arrangement_recorder import (
        ArrangementRecorder, RecordingState, 
        RecordingConfig
    )
    _arrangement_recorder_loaded = True
    _mark_available("arrangement_recorder")
except ImportError as e:
    _mark_missing("arrangement_recorder")
    logger.debug(f"arrangement_recorder not available: {e}")
    
    from enum import Enum
    
    class RecordingState(Enum):
        """Placeholder enum for recording state."""
        IDLE = "idle"
        RECORDING = "recording"
        PAUSED = "paused"
        ERROR = "error"
    
    class RecordingConfig:
        """Placeholder configuration class."""
        def __init__(self, *args, **kwargs):
            pass
    
    class ArrangementRecorder:
        """Placeholder - arrangement_recorder module not available."""
        def __init__(self, *args, **kwargs):
            raise ImportError("arrangement_recorder module not available")
        
        @property
        def state(self) -> RecordingState:
            return RecordingState.IDLE

# Live Bridge
_live_bridge_loaded = False
try:
    from .live_bridge import AbletonLiveBridge
    _live_bridge_loaded = True
    _mark_available("live_bridge")
except ImportError as e:
    _mark_missing("live_bridge")
    logger.debug(f"live_bridge not available: {e}")
    
    class AbletonLiveBridge:
        """Placeholder - live_bridge module not available."""
        def __init__(self, *args, **kwargs):
            raise ImportError("live_bridge module not available")

# Parameter Discovery (Agent 9)
_parameter_discovery_loaded = False
try:
    from .parameter_discovery import (
        ParameterDiscovery,
        DeviceParameter,
        DeviceInfo,
        discover_parameters,
        match_parameter,
    )
    _parameter_discovery_loaded = True
    _mark_available("parameter_discovery")
except ImportError as e:
    _mark_missing("parameter_discovery")
    logger.debug(f"parameter_discovery not available: {e}")
    
    class ParameterDiscovery:
        """Placeholder - parameter_discovery module not available."""
        def __init__(self, *args, **kwargs):
            raise ImportError("parameter_discovery module not available")
    
    class DeviceParameter:
        """Placeholder - parameter_discovery module not available."""
        pass
    
    class DeviceInfo:
        """Placeholder - parameter_discovery module not available."""
        pass
    
    def discover_parameters(*args, **kwargs):
        raise ImportError("parameter_discovery module not available")
    
    def match_parameter(*args, **kwargs):
        raise ImportError("parameter_discovery module not available")

# =============================================================================
# SENIOR ARCHITECTURE - INTELLIGENT SELECTION SYSTEM
# =============================================================================

# Intelligent Sample Selector
_intelligent_selector_loaded = False
try:
    from .intelligent_selector import (
        IntelligentSampleSelector,
        CoherenceError,
        select_coherent_kit,
        find_similar_samples as intelligent_find_similar,
        select_expansive_kit
    )
    _intelligent_selector_loaded = True
    _mark_available("intelligent_selector")
except ImportError as e:
    _mark_missing("intelligent_selector")
    logger.debug(f"intelligent_selector not available: {e}")
    
    class IntelligentSampleSelector:
        """Placeholder - intelligent_selector module not available."""
        def __init__(self, *args, **kwargs):
            raise ImportError("intelligent_selector module not available")
    
    class CoherenceError(Exception):
        """Placeholder - raised when samples lack coherence."""
        pass
    
    def select_coherent_kit(*args, **kwargs):
        raise ImportError("intelligent_selector module not available")
    
    def intelligent_find_similar(*args, **kwargs):
        raise ImportError("intelligent_selector module not available")
    
    def select_expansive_kit(*args, **kwargs):
        raise ImportError("intelligent_selector module not available")

# Coherence Scorer
_coherence_scorer_loaded = False
try:
    from .coherence_scorer import (
        CoherenceScorer,
        score_kit_coherence,
        is_professional_grade,
        MIN_COHERENCE
    )
    _coherence_scorer_loaded = True
    _mark_available("coherence_scorer")
except ImportError as e:
    _mark_missing("coherence_scorer")
    logger.debug(f"coherence_scorer not available: {e}")
    
    class CoherenceScorer:
        """Placeholder - coherence_scorer module not available."""
        def __init__(self, *args, **kwargs):
            raise ImportError("coherence_scorer module not available")
    
    def score_kit_coherence(*args, **kwargs):
        raise ImportError("coherence_scorer module not available")
    
    def is_professional_grade(*args, **kwargs):
        return False
    
    MIN_COHERENCE = 0.7

# Variation Engine (Sample Kit Evolution)
_variation_engine_loaded = False
try:
    from .variation_engine import (
        VariationEngine,
        SectionKit,
        EnergyCharacteristics,
        CoherenceMetrics,
        SECTION_PROFILES,
        evolve_kit_for_sections,
        get_section_energy_profile,
        validate_coherence,
    )
    _variation_engine_loaded = True
    _mark_available("variation_engine")
except ImportError as e:
    _mark_missing("variation_engine")
    logger.debug(f"variation_engine not available: {e}")
    
    class VariationEngine:
        """Placeholder - variation_engine module not available."""
        def __init__(self, *args, **kwargs):
            raise ImportError("variation_engine module not available")
    
    class SectionKit:
        """Placeholder - variation_engine module not available."""
        pass
    
    class EnergyCharacteristics:
        """Placeholder - variation_engine module not available."""
        pass
    
    class CoherenceMetrics:
        """Placeholder - variation_engine module not available."""
        pass
    
    SECTION_PROFILES = {}
    
    def evolve_kit_for_sections(*args, **kwargs):
        raise ImportError("variation_engine module not available")
    
    def get_section_energy_profile(*args, **kwargs):
        raise ImportError("variation_engine module not available")
    
    def validate_coherence(*args, **kwargs):
        return 0.0

# SPRINT 4 - EXPANSIVE SAMPLE SYSTEM (12 Samples per Category)
# =============================================================================

# SPRINT 5 - ADVANCED ENGINES (Library Indexing, MIDI Orchestration, DJ Structure, etc.)
# =============================================================================

# Library Indexer - Fast sample library indexing and search
_library_indexer_loaded = False
try:
    from .library_indexer import (
        LibraryIndexer,
        init_library_indexer,
    )
    _library_indexer_loaded = True
    _mark_available("library_indexer")
except ImportError as e:
    _mark_missing("library_indexer")
    logger.debug(f"library_indexer not available: {e}")
    
    class LibraryIndexer:
        """Placeholder - library_indexer module not available."""
        def __init__(self, *args, **kwargs):
            raise ImportError("library_indexer module not available")
    
    def init_library_indexer(*args, **kwargs):
        raise ImportError("library_indexer module not available")

# Massive Selector - Selects massive sample sets (20+ per category)
_massive_selector_loaded = False
try:
    from .massive_selector import (
        MassiveSelector,
        init_massive_selector,
    )
    _massive_selector_loaded = True
    _mark_available("massive_selector")
except ImportError as e:
    _mark_missing("massive_selector")
    logger.debug(f"massive_selector not available: {e}")
    
    class MassiveSelector:
        """Placeholder - massive_selector module not available."""
        def __init__(self, *args, **kwargs):
            raise ImportError("massive_selector module not available")
    
    def init_massive_selector(*args, **kwargs):
        raise ImportError("massive_selector module not available")

# Drum Layer Engine - Multi-layer drum sound design
_drum_layer_engine_loaded = False
try:
    from .drum_layer_engine import (
        DrumLayerEngine,
        init_drum_layer_engine,
    )
    _drum_layer_engine_loaded = True
    _mark_available("drum_layer_engine")
except ImportError as e:
    _mark_missing("drum_layer_engine")
    logger.debug(f"drum_layer_engine not available: {e}")
    
    class DrumLayerEngine:
        """Placeholder - drum_layer_engine module not available."""
        def __init__(self, *args, **kwargs):
            raise ImportError("drum_layer_engine module not available")
    
    def init_drum_layer_engine(*args, **kwargs):
        raise ImportError("drum_layer_engine module not available")

# MIDI Orchestrator - MIDI file orchestration and arrangement
_midi_orchestrator_loaded = False
try:
    from .midi_orchestrator import (
        MIDIOrchestrator,
        init_midi_orchestrator,
    )
    _midi_orchestrator_loaded = True
    _mark_available("midi_orchestrator")
except ImportError as e:
    _mark_missing("midi_orchestrator")
    logger.debug(f"midi_orchestrator not available: {e}")
    
    class MIDIOrchestrator:
        """Placeholder - midi_orchestrator module not available."""
        def __init__(self, *args, **kwargs):
            raise ImportError("midi_orchestrator module not available")
    
    def init_midi_orchestrator(*args, **kwargs):
        raise ImportError("midi_orchestrator module not available")

# DJ Structure Engine - DJ-friendly extended structures
_dj_structure_engine_loaded = False
try:
    from .dj_structure_engine import (
        DJStructureEngine,
        init_dj_structure_engine,
    )
    _dj_structure_engine_loaded = True
    _mark_available("dj_structure_engine")
except ImportError as e:
    _mark_missing("dj_structure_engine")
    logger.debug(f"dj_structure_engine not available: {e}")
    
    class DJStructureEngine:
        """Placeholder - dj_structure_engine module not available."""
        def __init__(self, *args, **kwargs):
            raise ImportError("dj_structure_engine module not available")
    
    def init_dj_structure_engine(*args, **kwargs):
        raise ImportError("dj_structure_engine module not available")

# Massive Injector - Inject massive sample sets into Arrangement View
_massive_injector_loaded = False
try:
    from .massive_injector import (
        MassiveInjector,
        init_massive_injector,
    )
    _massive_injector_loaded = True
    _mark_available("massive_injector")
except ImportError as e:
    _mark_missing("massive_injector")
    logger.debug(f"massive_injector not available: {e}")
    
    class MassiveInjector:
        """Placeholder - massive_injector module not available."""
        def __init__(self, *args, **kwargs):
            raise ImportError("massive_injector module not available")
    
    def init_massive_injector(*args, **kwargs):
        raise ImportError("massive_injector module not available")

# Advanced Automation - Sophisticated automation curves and envelopes
_advanced_automation_loaded = False
try:
    from .advanced_automation import (
        AdvancedAutomation,
        init_advanced_automation,
    )
    _advanced_automation_loaded = True
    _mark_available("advanced_automation")
except ImportError as e:
    _mark_missing("advanced_automation")
    logger.debug(f"advanced_automation not available: {e}")
    
    class AdvancedAutomation:
        """Placeholder - advanced_automation module not available."""
        def __init__(self, *args, **kwargs):
            raise ImportError("advanced_automation module not available")
    
    def init_advanced_automation(*args, **kwargs):
        raise ImportError("advanced_automation module not available")

# Ambience Generator - Ambient texture and atmosphere generation
_ambience_generator_loaded = False
try:
    from .ambience_generator import (
        AmbienceGenerator,
        init_ambience_generator,
    )
    _ambience_generator_loaded = True
    _mark_available("ambience_generator")
except ImportError as e:
    _mark_missing("ambience_generator")
    logger.debug(f"ambience_generator not available: {e}")
    
    class AmbienceGenerator:
        """Placeholder - ambience_generator module not available."""
        def __init__(self, *args, **kwargs):
            raise ImportError("ambience_generator module not available")
    
    def init_ambience_generator(*args, **kwargs):
        raise ImportError("ambience_generator module not available")

# Section Sample Mapper
_section_sample_mapper_loaded = False
try:
    from .section_sample_mapper import (
        SectionSampleMapper,
        SectionConfig,
        init_section_sample_mapper,
    )
    _section_sample_mapper_loaded = True
    _mark_available("section_sample_mapper")
except ImportError as e:
    _mark_missing("section_sample_mapper")
    logger.debug(f"section_sample_mapper not available: {e}")
    
    class SectionSampleMapper:
        """Placeholder - section_sample_mapper module not available."""
        def __init__(self, *args, **kwargs):
            raise ImportError("section_sample_mapper module not available")
    
    class SectionConfig:
        """Placeholder - section_sample_mapper module not available."""
        pass
    
    def init_section_sample_mapper(*args, **kwargs):
        raise ImportError("section_sample_mapper module not available")

# Expansive Coherence Validator
_expansive_coherence_validator_loaded = False
try:
    from .expansive_coherence_validator import (
        ExpansiveCoherenceValidator,
        init_expansive_coherence_validator,
    )
    _expansive_coherence_validator_loaded = True
    _mark_available("expansive_coherence_validator")
except ImportError as e:
    _mark_missing("expansive_coherence_validator")
    logger.debug(f"expansive_coherence_validator not available: {e}")
    
    class ExpansiveCoherenceValidator:
        """Placeholder - expansive_coherence_validator module not available."""
        def __init__(self, *args, **kwargs):
            raise ImportError("expansive_coherence_validator module not available")
    
    def init_expansive_coherence_validator(*args, **kwargs):
        raise ImportError("expansive_coherence_validator module not available")

# Multi-Sample Injector
_multi_sample_injector_loaded = False
try:
    from .multi_sample_injector import (
        MultiSampleInjector,
        InjectionPlan,
        RotationMode,
        init_multi_sample_injector,
    )
    _multi_sample_injector_loaded = True
    _mark_available("multi_sample_injector")
except ImportError as e:
    _mark_missing("multi_sample_injector")
    logger.debug(f"multi_sample_injector not available: {e}")
    
    class MultiSampleInjector:
        """Placeholder - multi_sample_injector module not available."""
        def __init__(self, *args, **kwargs):
            raise ImportError("multi_sample_injector module not available")
    
    class InjectionPlan:
        """Placeholder - multi_sample_injector module not available."""
        pass
    
    class RotationMode:
        """Placeholder - multi_sample_injector module not available."""
        pass
    
    def init_multi_sample_injector(*args, **kwargs):
        raise ImportError("multi_sample_injector module not available")

# Section Builder Real - Real-time section building in Ableton
_section_builder_real_loaded = False
try:
    from .section_builder_real import (
        SectionBuilderReal,
        SectionBuildReport,
        create_section_builder,
    )
    _section_builder_real_loaded = True
    _mark_available("section_builder_real")
except ImportError as e:
    _mark_missing("section_builder_real")
    logger.debug(f"section_builder_real not available: {e}")
    
    class SectionBuilderReal:
        """Placeholder - section_builder_real module not available."""
        def __init__(self, *args, **kwargs):
            raise ImportError("section_builder_real module not available")
    
    class SectionBuildReport:
        """Placeholder - section_builder_real module not available."""
        pass
    
    def create_section_builder(*args, **kwargs):
        raise ImportError("section_builder_real module not available")

# Variation Controller
_variation_controller_loaded = False
try:
    from .variation_controller import (
        VariationController,
        VariationConfig,
        init_variation_controller,
    )
    _variation_controller_loaded = True
    _mark_available("variation_controller")
except ImportError as e:
    _mark_missing("variation_controller")
    logger.debug(f"variation_controller not available: {e}")
    
    class VariationController:
        """Placeholder - variation_controller module not available."""
        def __init__(self, *args, **kwargs):
            raise ImportError("variation_controller module not available")
    
    class VariationConfig:
        """Placeholder - variation_controller module not available."""
        pass
    
    def init_variation_controller(*args, **kwargs):
        raise ImportError("variation_controller module not available")

# =============================================================================
# SPRINT 5.5 - ADVANCED PRODUCTION ENGINES (Micro-Batch, Real-Time, Export)
# =============================================================================

# Micro Batch Injector - Efficient batch sample injection
_micro_batch_injector_loaded = False
try:
    from .micro_batch_injector import (
        MicroBatchInjector,
        BatchInjectionPlan,
        init_micro_batch_injector,
    )
    _micro_batch_injector_loaded = True
    _mark_available("micro_batch_injector")
except ImportError as e:
    _mark_missing("micro_batch_injector")
    logger.debug(f"micro_batch_injector not available: {e}")
    
    class MicroBatchInjector:
        """Placeholder - micro_batch_injector module not available."""
        def __init__(self, *args, **kwargs):
            raise ImportError("micro_batch_injector module not available")
    
    class BatchInjectionPlan:
        """Placeholder - micro_batch_injector module not available."""
        pass
    
    def init_micro_batch_injector(*args, **kwargs):
        raise ImportError("micro_batch_injector module not available")

# Real Coherence Validator - Real-time coherence validation
_real_coherence_validator_loaded = False
try:
    from .real_coherence_validator import (
        RealCoherenceValidator,
        ValidationResult,
        init_real_coherence_validator,
    )
    _real_coherence_validator_loaded = True
    _mark_available("real_coherence_validator")
except ImportError as e:
    _mark_missing("real_coherence_validator")
    logger.debug(f"real_coherence_validator not available: {e}")
    
    class RealCoherenceValidator:
        """Placeholder - real_coherence_validator module not available."""
        def __init__(self, *args, **kwargs):
            raise ImportError("real_coherence_validator module not available")
    
    class ValidationResult:
        """Placeholder - real_coherence_validator module not available."""
        pass
    
    def init_real_coherence_validator(*args, **kwargs):
        raise ImportError("real_coherence_validator module not available")

# Session Validator - Comprehensive Session View validation
_session_validator_loaded = False
try:
    from .session_validator import (
        SessionValidator,
        ValidationResult as SessionValidationResult,
        validate_session_production,
    )
    _session_validator_loaded = True
    _mark_available("session_validator")
except ImportError as e:
    _mark_missing("session_validator")
    logger.debug(f"session_validator not available: {e}")
    
    class SessionValidator:
        """Placeholder - session_validator module not available."""
        def __init__(self, *args, **kwargs):
            raise ImportError("session_validator module not available")
    
    def validate_session_production(*args, **kwargs):
        raise ImportError("session_validator module not available")

# Smart Sample Selector - Intelligent sample selection with coherence
_smart_sample_selector_loaded = False
try:
    from .smart_sample_selector import (
        SmartSampleSelector,
        SelectionCriteria,
        init_smart_sample_selector,
    )
    _smart_sample_selector_loaded = True
    _mark_available("smart_sample_selector")
except ImportError as e:
    _mark_missing("smart_sample_selector")
    logger.debug(f"smart_sample_selector not available: {e}")
    
    class SmartSampleSelector:
        """Placeholder - smart_sample_selector module not available."""
        def __init__(self, *args, **kwargs):
            raise ImportError("smart_sample_selector module not available")
    
    class SelectionCriteria:
        """Placeholder - smart_sample_selector module not available."""
        pass
    
    def init_smart_sample_selector(*args, **kwargs):
        raise ImportError("smart_sample_selector module not available")

# Realtime Progress Tracker - Track production progress in real-time
_realtime_progress_tracker_loaded = False
try:
    from .realtime_progress_tracker import (
        RealtimeProgressTracker,
        ProgressStage,
        init_realtime_progress_tracker,
    )
    _realtime_progress_tracker_loaded = True
    _mark_available("realtime_progress_tracker")
except ImportError as e:
    _mark_missing("realtime_progress_tracker")
    logger.debug(f"realtime_progress_tracker not available: {e}")
    
    class RealtimeProgressTracker:
        """Placeholder - realtime_progress_tracker module not available."""
        def __init__(self, *args, **kwargs):
            raise ImportError("realtime_progress_tracker module not available")
    
    class ProgressStage:
        """Placeholder - realtime_progress_tracker module not available."""
        pass
    
    def init_realtime_progress_tracker(*args, **kwargs):
        raise ImportError("realtime_progress_tracker module not available")

# Section Automation - Automated section parameter control
_section_automation_loaded = False
try:
    from .section_automation import (
        SectionAutomation,
        AutomationEnvelope,
        init_section_automation,
    )
    _section_automation_loaded = True
    _mark_available("section_automation")
except ImportError as e:
    _mark_missing("section_automation")
    logger.debug(f"section_automation not available: {e}")
    
    class SectionAutomation:
        """Placeholder - section_automation module not available."""
        def __init__(self, *args, **kwargs):
            raise ImportError("section_automation module not available")
    
    def init_section_automation(*args, **kwargs):
        raise ImportError("section_automation module not available")

# Export Engine - Professional export and rendering
_export_engine_loaded = False
try:
    from .export_engine import (
        ExportEngine,
        ExportConfig,
        RenderFormat,
        init_export_engine,
    )
    _export_engine_loaded = True
    _mark_available("export_engine")
except ImportError as e:
    _mark_missing("export_engine")
    logger.debug(f"export_engine not available: {e}")
    
    class ExportEngine:
        """Placeholder - export_engine module not available."""
        def __init__(self, *args, **kwargs):
            raise ImportError("export_engine module not available")
    
    class ExportConfig:
        """Placeholder - export_engine module not available."""
        pass
    
    class RenderFormat:
        """Placeholder - export_engine module not available."""
        WAV = "wav"
        AIFF = "aiff"
        FLAC = "flac"
        MP3 = "mp3"
    
    def init_export_engine(*args, **kwargs):
        raise ImportError("export_engine module not available")

# Master Orchestrator Sprint 5.5 - Central production orchestration
_master_orchestrator_sprint55_loaded = False
try:
    from .master_orchestrator_sprint55 import (
        MasterOrchestratorSprint55,
        OrchestrationConfig,
        ProductionStage,
        init_master_orchestrator_sprint55,
    )
    _master_orchestrator_sprint55_loaded = True
    _mark_available("master_orchestrator_sprint55")
except ImportError as e:
    _mark_missing("master_orchestrator_sprint55")
    logger.debug(f"master_orchestrator_sprint55 not available: {e}")
    
    class MasterOrchestratorSprint55:
        """Placeholder - master_orchestrator_sprint55 module not available."""
        def __init__(self, *args, **kwargs):
            raise ImportError("master_orchestrator_sprint55 module not available")
    
    class OrchestrationConfig:
        """Placeholder - master_orchestrator_sprint55 module not available."""
        pass
    
    class ProductionStage:
        """Placeholder - master_orchestrator_sprint55 module not available."""
        pass
    
    def init_master_orchestrator_sprint55(*args, **kwargs):
        raise ImportError("master_orchestrator_sprint55 module not available")

# =============================================================================
# FASES 6-9: Session Orchestrator + Warp Automation + Full MIDI Orchestration
# =============================================================================

# BPM Analyzer Initialization
_bpm_analyzer_instance = None

def init_bpm_analyzer(library_path: Optional[str] = None) -> 'BPMAnalyzer':
    """
    Initialize and return BPM analyzer singleton.
    
    Args:
        library_path: Optional path to the sample library
    
    Returns:
        BPMAnalyzer instance (cached singleton)
    """
    global _bpm_analyzer_instance
    if _bpm_analyzer_instance is None:
        if not _bpm_analyzer_loaded:
            raise ImportError(
                "bpm_analyzer module not available. "
                "Ensure bpm_analyzer.py is present in engines/"
            )
        analyzer = BPMAnalyzer(library_path=library_path)
        _bpm_analyzer_instance = analyzer
        logger.info(f"Initialized BPM analyzer (path: {library_path or 'default'})")
    return _bpm_analyzer_instance

def get_bpm_analyzer() -> Optional['BPMAnalyzer']:
    """Get existing BPM analyzer instance or None if not initialized."""
    return _bpm_analyzer_instance

# Spectral Coherence Initialization
_spectral_coherence_instance = None

def init_spectral_coherence() -> 'SpectralCoherence':
    """
    Initialize and return spectral coherence analyzer singleton.
    
    Returns:
        SpectralCoherence instance (cached singleton)
    """
    global _spectral_coherence_instance
    if _spectral_coherence_instance is None:
        if not _spectral_coherence_loaded:
            raise ImportError(
                "spectral_coherence module not available. "
                "Ensure spectral_coherence.py is present in engines/"
            )
        coherence = SpectralCoherence()
        _spectral_coherence_instance = coherence
        logger.info("Initialized spectral coherence analyzer")
    return _spectral_coherence_instance

def get_spectral_coherence() -> Optional['SpectralCoherence']:
    """Get existing spectral coherence instance or None if not initialized."""
    return _spectral_coherence_instance

# Session Orchestrator Initialization
_session_orchestrator_instance = None

def init_session_orchestrator(connection=None) -> 'SessionOrchestrator':
    """
    Initialize and return session orchestrator singleton.
    
    Args:
        connection: Optional Ableton TCP connection
    
    Returns:
        SessionOrchestrator instance (cached singleton)
    """
    global _session_orchestrator_instance
    if _session_orchestrator_instance is None:
        if not _session_orchestrator_loaded:
            raise ImportError(
                "session_orchestrator module not available. "
                "Ensure session_orchestrator.py is present in engines/"
            )
        orchestrator = SessionOrchestrator(connection=connection)
        _session_orchestrator_instance = orchestrator
        logger.info("Initialized session orchestrator")
    return _session_orchestrator_instance

def get_session_orchestrator() -> Optional['SessionOrchestrator']:
    """Get existing session orchestrator instance or None if not initialized."""
    return _session_orchestrator_instance

# Rationale Logger
_rationale_logger_loaded = False
try:
    from .rationale_logger import (
        RationaleLogger,
        log_sample_selection,
        log_kit_assembly,
        get_session_rationale
    )
    _rationale_logger_loaded = True
    _mark_available("rationale_logger")
except ImportError as e:
    _mark_missing("rationale_logger")
    logger.debug(f"rationale_logger not available: {e}")

# =============================================================================
# FASES 6-9: Session Orchestrator + Warp Automation + Full MIDI Orchestration
# =============================================================================

# BPM Analyzer
_bpm_analyzer_loaded = False
try:
    from .bpm_analyzer import (
        BPMAnalyzer,
        analyze_sample,
        init_bpm_analyzer,
        get_bpm_analyzer,
    )
    _bpm_analyzer_loaded = True
    _mark_available("bpm_analyzer")
except ImportError as e:
    _mark_missing("bpm_analyzer")
    logger.debug(f"bpm_analyzer not available: {e}")
    
    class BPMAnalyzer:
        """Placeholder - bpm_analyzer module not available."""
        def __init__(self, *args, **kwargs):
            raise ImportError("bpm_analyzer module not available")
    
    def analyze_sample(*args, **kwargs):
        raise ImportError("bpm_analyzer module not available")
    
    def init_bpm_analyzer(*args, **kwargs):
        raise ImportError("bpm_analyzer module not available")
    
    def get_bpm_analyzer(*args, **kwargs):
        raise ImportError("bpm_analyzer module not available")

# Spectral Coherence
_spectral_coherence_loaded = False
try:
    from .spectral_coherence import (
        SpectralCoherence,
        get_sample_similarity,
        init_spectral_coherence,
        get_spectral_coherence,
    )
    _spectral_coherence_loaded = True
    _mark_available("spectral_coherence")
except ImportError as e:
    _mark_missing("spectral_coherence")
    logger.debug(f"spectral_coherence not available: {e}")
    
    class SpectralCoherence:
        """Placeholder - spectral_coherence module not available."""
        def __init__(self, *args, **kwargs):
            raise ImportError("spectral_coherence module not available")
    
    def get_sample_similarity(*args, **kwargs):
        raise ImportError("spectral_coherence module not available")
    
    def init_spectral_coherence(*args, **kwargs):
        raise ImportError("spectral_coherence module not available")
    
    def get_spectral_coherence(*args, **kwargs):
        raise ImportError("spectral_coherence module not available")

# Session Orchestrator
_session_orchestrator_loaded = False
try:
    from .session_orchestrator import (
        SessionOrchestrator,
        validate_and_fix_track,
        init_session_orchestrator,
        get_session_orchestrator,
    )
    _session_orchestrator_loaded = True
    _mark_available("session_orchestrator")
except ImportError as e:
    _mark_missing("session_orchestrator")
    logger.debug(f"session_orchestrator not available: {e}")
    
    class SessionOrchestrator:
        """Placeholder - session_orchestrator module not available."""
        def __init__(self, *args, **kwargs):
            raise ImportError("session_orchestrator module not available")
    
    def validate_and_fix_track(*args, **kwargs):
        raise ImportError("session_orchestrator module not available")
    
    def init_session_orchestrator(*args, **kwargs):
        raise ImportError("session_orchestrator module not available")
    
    def get_session_orchestrator(*args, **kwargs):
        raise ImportError("session_orchestrator module not available")
    
    class RationaleLogger:
        """Placeholder - rationale_logger module not available."""
        def __init__(self, *args, **kwargs):
            raise ImportError("rationale_logger module not available")
    
    def log_sample_selection(*args, **kwargs):
        pass
    
    def log_kit_assembly(*args, **kwargs):
        pass
    
    def get_session_rationale(*args, **kwargs):
        return {}

# Preset Manager
_preset_manager_loaded = False
try:
    from .preset_manager import (
        PresetManager,
        save_kit_preset,
        load_kit_preset,
        list_presets,
        KitPreset
    )
    _preset_manager_loaded = True
    _mark_available("preset_manager")
except ImportError as e:
    _mark_missing("preset_manager")
    logger.debug(f"preset_manager not available: {e}")
    
    class PresetManager:
        """Placeholder - preset_manager module not available."""
        def __init__(self, *args, **kwargs):
            raise ImportError("preset_manager module not available")
    
    class KitPreset:
        """Placeholder - preset_manager module not available."""
        pass
    
    def save_kit_preset(*args, **kwargs):
        raise ImportError("preset_manager module not available")
    
    def load_kit_preset(*args, **kwargs):
        raise ImportError("preset_manager module not available")
    
    def list_presets(*args, **kwargs):
        return []

# Iteration Engine
_iteration_engine_loaded = False
try:
    from .iteration_engine import (
        IterationEngine,
        iterate_until_coherence,
        ProfessionalCoherenceError,
        ITERATION_STRATEGIES
    )
    _iteration_engine_loaded = True
    _mark_available("iteration_engine")
except ImportError as e:
    _mark_missing("iteration_engine")
    logger.debug(f"iteration_engine not available: {e}")
    
    class IterationEngine:
        """Placeholder - iteration_engine module not available."""
        def __init__(self, *args, **kwargs):
            raise ImportError("iteration_engine module not available")
    
    class ProfessionalCoherenceError(Exception):
        """Placeholder - raised when professional coherence cannot be achieved."""
        pass
    
    def iterate_until_coherence(*args, **kwargs):
        raise ImportError("iteration_engine module not available")
    
    ITERATION_STRATEGIES = []

# =============================================================================
# SENIOR ARCHITECTURE - NEW MODULES (Coherence System, Audio Analyzer Dual, Bus Architecture)
# =============================================================================

# Coherence System
coherence_system_loaded = False
try:
    # Try relative import first (for normal Python usage)
    from .coherence_system import (
        calculate_joint_score,
        update_cross_generation_memory,
        get_cross_generation_penalty,
        get_persistent_fatigue,
        ROLE_ACTIVITY,
        SECTION_DENSITY_PROFILES,
        get_section_role_bonus,
        calculate_section_appropriateness,
        set_palette_lock,
        calculate_palette_bonus,
        get_palette_coherence_score,
        calculate_comprehensive_coherence,
        reset_all_memory,
        get_coherence_memory_stats
    )
    coherence_system_loaded = True
    _mark_available("coherence_system")
except ImportError:
    # Fallback to absolute import (for Ableton runtime)
    try:
        from coherence_system import (
            calculate_joint_score,
            update_cross_generation_memory,
            get_cross_generation_penalty,
            get_persistent_fatigue,
            ROLE_ACTIVITY,
            SECTION_DENSITY_PROFILES,
            get_section_role_bonus,
            calculate_section_appropriateness,
            set_palette_lock,
            calculate_palette_bonus,
            get_palette_coherence_score,
            calculate_comprehensive_coherence,
            reset_all_memory,
            get_coherence_memory_stats
        )
        coherence_system_loaded = True
        _mark_available("coherence_system")
    except ImportError as e:
        _mark_missing("coherence_system")
        logger.debug(f"coherence_system not available: {e}")
    
    # Define placeholder functions
    def calculate_joint_score(*args, **kwargs):
        raise ImportError("coherence_system module not available")
    def update_cross_generation_memory(*args, **kwargs):
        pass
    def get_cross_generation_penalty(*args, **kwargs):
        return 0.0
    def get_persistent_fatigue(*args, **kwargs):
        return 0.0
    ROLE_ACTIVITY = {}
    SECTION_DENSITY_PROFILES = {}
    def get_section_role_bonus(*args, **kwargs):
        return 0.0
    def calculate_section_appropriateness(*args, **kwargs):
        return 0.5
    def set_palette_lock(*args, **kwargs):
        pass
    def calculate_palette_bonus(*args, **kwargs):
        return 0.0
    def get_palette_coherence_score(*args, **kwargs):
        return 0.0
    def calculate_comprehensive_coherence(*args, **kwargs):
        return 0.7
    def reset_all_memory():
        pass
    def get_coherence_memory_stats():
        return {}

# Audio Analyzer Dual
audio_analyzer_dual_loaded = False
try:
    # Try relative import first (for normal Python usage)
    from .audio_analyzer_dual import (
        AudioAnalyzerDual,
        AudioFeatures,
        analyze_sample,
        analyze_audio,
        get_backend_info
    )
    audio_analyzer_dual_loaded = True
    _mark_available("audio_analyzer_dual")
except ImportError:
    # Fallback to absolute import (for Ableton runtime)
    try:
        from audio_analyzer_dual import (
            AudioAnalyzerDual,
            AudioFeatures,
            analyze_sample,
            analyze_audio,
            get_backend_info
        )
        audio_analyzer_dual_loaded = True
        _mark_available("audio_analyzer_dual")
    except ImportError as e:
        _mark_missing("audio_analyzer_dual")
        logger.debug(f"audio_analyzer_dual not available: {e}")
    
    class AudioAnalyzerDual:
        """Placeholder - audio_analyzer_dual module not available."""
        def __init__(self, *args, **kwargs):
            raise ImportError("audio_analyzer_dual module not available")
    
    class AudioFeatures:
        """Placeholder - audio_analyzer_dual module not available."""
        def __init__(self, *args, **kwargs):
            raise ImportError("audio_analyzer_dual module not available")
    
    def analyze_sample(*args, **kwargs):
        raise ImportError("audio_analyzer_dual module not available")
    
    def analyze_audio(*args, **kwargs):
        raise ImportError("audio_analyzer_dual module not available")
    
    def get_backend_info():
        return {"available": False, "backend": "none"}

# Bus Architecture
bus_architecture_loaded = False
try:
    # Try relative import first (for normal Python usage)
    from .bus_architecture import (
        BUS_GAIN_CALIBRATION,
        RETURN_CONFIG,
        ROLE_MIX,
        MASTER_CHAIN,
        BusArchitecture,
        create_bus_track,
        create_return_track,
        route_track_to_bus,
        set_track_send,
        configure_bus_gain,
        configure_return_effect,
        apply_role_mix,
        configure_master_chain,
        apply_professional_mix,
        get_bus_config,
        get_return_config,
        get_role_mix,
        list_available_buses,
        list_available_returns,
        list_available_roles
    )
    bus_architecture_loaded = True
    _mark_available("bus_architecture")
except ImportError:
    # Fallback to absolute import (for Ableton runtime)
    try:
        from bus_architecture import (
            BUS_GAIN_CALIBRATION,
            RETURN_CONFIG,
            ROLE_MIX,
            MASTER_CHAIN,
            BusArchitecture,
            create_bus_track,
            create_return_track,
            route_track_to_bus,
            set_track_send,
            configure_bus_gain,
            configure_return_effect,
            apply_role_mix,
            configure_master_chain,
            apply_professional_mix,
            get_bus_config,
            get_return_config,
            get_role_mix,
            list_available_buses,
            list_available_returns,
            list_available_roles
        )
        bus_architecture_loaded = True
        _mark_available("bus_architecture")
    except ImportError as e:
        _mark_missing("bus_architecture")
        logger.debug(f"bus_architecture not available: {e}")
    
    BUS_GAIN_CALIBRATION = {}
    RETURN_CONFIG = {}
    ROLE_MIX = {}
    MASTER_CHAIN = {}
    
    class BusArchitecture:
        """Placeholder - bus_architecture module not available."""
        def __init__(self, *args, **kwargs):
            raise ImportError("bus_architecture module not available")
    
    def create_bus_track(*args, **kwargs):
        raise ImportError("bus_architecture module not available")
    def create_return_track(*args, **kwargs):
        raise ImportError("bus_architecture module not available")
    def route_track_to_bus(*args, **kwargs):
        raise ImportError("bus_architecture module not available")
    def set_track_send(*args, **kwargs):
        raise ImportError("bus_architecture module not available")
    def configure_bus_gain(*args, **kwargs):
        raise ImportError("bus_architecture module not available")
    def configure_return_effect(*args, **kwargs):
        raise ImportError("bus_architecture module not available")
    def apply_role_mix(*args, **kwargs):
        raise ImportError("bus_architecture module not available")
    def configure_master_chain(*args, **kwargs):
        raise ImportError("bus_architecture module not available")
    def apply_professional_mix(*args, **kwargs):
        raise ImportError("bus_architecture module not available")
    def get_bus_config():
        return {}
    def get_return_config():
        return {}
    def get_role_mix():
        return {}
    def list_available_buses():
        return []
    def list_available_returns():
        return []
    def list_available_roles():
        return []


# =============================================================================
# AGENTE 12 - VST/AU Plugin Support
# =============================================================================

_vst_manager_loaded = False
try:
    from .vst_manager import (
        VSTManager,
        PluginInfo,
        PluginType,
        PluginCategory,
        ParameterInfo,
        get_vst_manager,
        scan_vst_plugins,
        get_vst_presets,
        get_all_plugins,
        validate_plugin,
        get_plugin_parameters,
    )
    _vst_manager_loaded = True
    _mark_available("vst_manager")
except ImportError:
    # Fallback to absolute import (for Ableton runtime)
    try:
        from vst_manager import (
            VSTManager,
            PluginInfo,
            PluginType,
            PluginCategory,
            ParameterInfo,
            get_vst_manager,
            scan_vst_plugins,
            get_vst_presets,
            get_all_plugins,
            validate_plugin,
            get_plugin_parameters,
        )
        _vst_manager_loaded = True
        _mark_available("vst_manager")
    except ImportError as e:
        _mark_missing("vst_manager")
        logger.debug(f"vst_manager not available: {e}")

    # Define placeholders
    class VSTManager:
        """Placeholder - vst_manager module not available."""
        def __init__(self, *args, **kwargs):
            raise ImportError("vst_manager module not available")
    
    class PluginInfo:
        """Placeholder - vst_manager module not available."""
        pass
    
    class PluginType:
        """Placeholder - vst_manager module not available."""
        VST2 = "VST2"
        VST3 = "VST3"
        AU = "AU"
    
    class PluginCategory:
        """Placeholder - vst_manager module not available."""
        SYNTH = "synth"
        EFFECT = "effect"
        EQ = "eq"
        COMPRESSOR = "compressor"
        REVERB = "reverb"
        DELAY = "delay"
        UTILITY = "utility"
    
    class ParameterInfo:
        """Placeholder - vst_manager module not available."""
        pass
    
    def get_vst_manager(*args, **kwargs):
        raise ImportError("vst_manager module not available")
    
    def scan_vst_plugins(*args, **kwargs):
        raise ImportError("vst_manager module not available")
    
    def get_vst_presets(*args, **kwargs):
        raise ImportError("vst_manager module not available")
    
    def get_all_plugins(*args, **kwargs):
        raise ImportError("vst_manager module not available")
    
    def validate_plugin(*args, **kwargs):
        raise ImportError("vst_manager module not available")
    
    def get_plugin_parameters(*args, **kwargs):
        raise ImportError("vst_manager module not available")


# =============================================================================
# INITIALIZATION FUNCTIONS
# =============================================================================

# Singleton storage for initialized components
_initialized_components: Dict[str, Any] = {}

def init_metadata_store(db_path: Optional[str] = None) -> SampleMetadataStore:
    """
    Initialize and return metadata store singleton.
    
    Args:
        db_path: Optional path to SQLite database. Uses default if None.
    
    Returns:
        SampleMetadataStore instance (cached singleton)
    
    Raises:
        ImportError: If metadata_store module is not available
    """
    if "metadata_store" not in _initialized_components:
        if not _metadata_store_loaded:
            raise ImportError(
                "metadata_store module not available. "
                "Ensure metadata_store.py is present in engines/"
            )
        store = SampleMetadataStore(db_path=db_path)
        _initialized_components["metadata_store"] = store
        logger.info(f"Initialized metadata store with db: {db_path or 'default'}")
    
    return _initialized_components["metadata_store"]


def init_hybrid_extractor(db_path: Optional[str] = None) -> HybridExtractor:
    """
    Initialize hybrid extractor with database + optional librosa.
    
    This creates a HybridExtractor that combines database-backed
    metadata with runtime librosa analysis when available.
    
    Args:
        db_path: Optional path to metadata database
    
    Returns:
        HybridExtractor instance
    
    Raises:
        ImportError: If abstract_analyzer module is not available
    """
    if "hybrid_extractor" not in _initialized_components:
        if not _abstract_analyzer_loaded:
            raise ImportError(
                "abstract_analyzer module not available. "
                "Cannot create hybrid extractor."
            )
        
        # Initialize with database extractor
        store = init_metadata_store(db_path) if _metadata_store_loaded else None
        db_extractor = DatabaseExtractor(store) if store else None
        
        # Try to add librosa extractor if available
        librosa_extractor = None
        try:
            librosa_extractor = LibrosaExtractor()
            logger.info("Librosa extractor initialized")
        except ImportError:
            logger.warning("Librosa not available - hybrid extractor will use database only")
        
        # Create hybrid
        hybrid = HybridExtractor(
            database_extractor=db_extractor,
            librosa_extractor=librosa_extractor
        )
        
        _initialized_components["hybrid_extractor"] = hybrid
        logger.info("Initialized hybrid extractor")
    
    return _initialized_components["hybrid_extractor"]


def init_arrangement_recorder(song, connection) -> ArrangementRecorder:
    """
    Initialize arrangement recorder.
    
    Args:
        song: Ableton Live song object
        connection: TCP connection to Ableton
    
    Returns:
        ArrangementRecorder instance
    
    Raises:
        ImportError: If arrangement_recorder module is not available
    """
    if "arrangement_recorder" not in _initialized_components:
        if not _arrangement_recorder_loaded:
            raise ImportError(
                "arrangement_recorder module not available. "
                "Ensure arrangement_recorder.py is present in engines/"
            )
        
        recorder = ArrangementRecorder(song=song, connection=connection)
        _initialized_components["arrangement_recorder"] = recorder
        logger.info("Initialized arrangement recorder")
    
    return _initialized_components["arrangement_recorder"]


def init_live_bridge(song, connection) -> AbletonLiveBridge:
    """
    Initialize Live bridge for direct API access.
    
    Args:
        song: Ableton Live song object
        connection: TCP connection to Ableton
    
    Returns:
        AbletonLiveBridge instance
    
    Raises:
        ImportError: If live_bridge module is not available
    """
    if "live_bridge" not in _initialized_components:
        if not _live_bridge_loaded:
            raise ImportError(
                "live_bridge module not available. "
                "Ensure live_bridge.py is present in engines/"
            )
        
        bridge = AbletonLiveBridge(song=song, connection=connection)
        _initialized_components["live_bridge"] = bridge
        logger.info("Initialized Live bridge")
    
    return _initialized_components["live_bridge"]


def init_intelligent_selector(
    coherence_scorer=None,
    variation_engine=None,
    rationale_logger=None
) -> IntelligentSampleSelector:
    """
    Initialize intelligent sample selector with optional dependencies.
    
    Args:
        coherence_scorer: Optional CoherenceScorer instance
        variation_engine: Optional VariationEngine instance
        rationale_logger: Optional RationaleLogger instance
    
    Returns:
        IntelligentSampleSelector instance
    
    Raises:
        ImportError: If intelligent_selector module is not available
    """
    if "intelligent_selector" not in _initialized_components:
        if not _intelligent_selector_loaded:
            raise ImportError(
                "intelligent_selector module not available. "
                "Ensure intelligent_selector.py is present in engines/"
            )
        
        # Initialize dependencies if not provided
        if coherence_scorer is None and _coherence_scorer_loaded:
            coherence_scorer = init_coherence_scorer()
        if variation_engine is None and _variation_engine_loaded:
            variation_engine = init_variation_engine()
        if rationale_logger is None and _rationale_logger_loaded:
            rationale_logger = init_rationale_logger()
        
        selector = IntelligentSampleSelector(
            coherence_scorer=coherence_scorer,
            variation_engine=variation_engine,
            rationale_logger=rationale_logger
        )
        _initialized_components["intelligent_selector"] = selector
        logger.info("Initialized intelligent sample selector")
    
    return _initialized_components["intelligent_selector"]


def init_coherence_scorer() -> CoherenceScorer:
    """
    Initialize coherence scorer for kit quality evaluation.
    
    Returns:
        CoherenceScorer instance
    
    Raises:
        ImportError: If coherence_scorer module is not available
    """
    if "coherence_scorer" not in _initialized_components:
        if not _coherence_scorer_loaded:
            raise ImportError(
                "coherence_scorer module not available. "
                "Ensure coherence_scorer.py is present in engines/"
            )
        
        scorer = CoherenceScorer()
        _initialized_components["coherence_scorer"] = scorer
        logger.info("Initialized coherence scorer")
    
    return _initialized_components["coherence_scorer"]


def init_variation_engine() -> VariationEngine:
    """
    Initialize variation engine for section-based kit evolution.
    
    Returns:
        VariationEngine instance
    
    Raises:
        ImportError: If variation_engine module is not available
    """
    if "variation_engine" not in _initialized_components:
        if not _variation_engine_loaded:
            raise ImportError(
                "variation_engine module not available. "
                "Ensure variation_engine.py is present in engines/"
            )
        
        engine = VariationEngine()
        _initialized_components["variation_engine"] = engine
        logger.info("Initialized variation engine")
    
    return _initialized_components["variation_engine"]


def init_rationale_logger(session_id: Optional[str] = None) -> RationaleLogger:
    """
    Initialize rationale logger for tracking selection decisions.
    
    Args:
        session_id: Optional session identifier for grouping logs
    
    Returns:
        RationaleLogger instance
    
    Raises:
        ImportError: If rationale_logger module is not available
    """
    if "rationale_logger" not in _initialized_components:
        if not _rationale_logger_loaded:
            raise ImportError(
                "rationale_logger module not available. "
                "Ensure rationale_logger.py is present in engines/"
            )
        
        logger_instance = RationaleLogger(session_id=session_id)
        _initialized_components["rationale_logger"] = logger_instance
        logger.info(f"Initialized rationale logger (session: {session_id or 'auto'})")
    
    return _initialized_components["rationale_logger"]


def init_preset_manager(presets_dir: Optional[str] = None) -> PresetManager:
    """
    Initialize preset manager for kit preset operations.
    
    Args:
        presets_dir: Optional directory path for storing presets
    
    Returns:
        PresetManager instance
    
    Raises:
        ImportError: If preset_manager module is not available
    """
    if "preset_manager" not in _initialized_components:
        if not _preset_manager_loaded:
            raise ImportError(
                "preset_manager module not available. "
                "Ensure preset_manager.py is present in engines/"
            )
        
        manager = PresetManager(presets_dir=presets_dir)
        _initialized_components["preset_manager"] = manager
        logger.info(f"Initialized preset manager (dir: {presets_dir or 'default'})")
    
    return _initialized_components["preset_manager"]


def init_iteration_engine(
    intelligent_selector=None,
    coherence_scorer=None,
    max_iterations: int = 10
) -> IterationEngine:
    """
    Initialize iteration engine for coherence-based iteration.
    
    Args:
        intelligent_selector: Optional IntelligentSampleSelector instance
        coherence_scorer: Optional CoherenceScorer instance
        max_iterations: Maximum number of iteration attempts
    
    Returns:
        IterationEngine instance
    
    Raises:
        ImportError: If iteration_engine module is not available
    """
    if "iteration_engine" not in _initialized_components:
        if not _iteration_engine_loaded:
            raise ImportError(
                "iteration_engine module not available. "
                "Ensure iteration_engine.py is present in engines/"
            )
        
        # Initialize dependencies if not provided
        if intelligent_selector is None and _intelligent_selector_loaded:
            intelligent_selector = init_intelligent_selector(coherence_scorer=coherence_scorer)
        if coherence_scorer is None and _coherence_scorer_loaded:
            coherence_scorer = init_coherence_scorer()
        
        engine = IterationEngine(
            selector=intelligent_selector,
            scorer=coherence_scorer,
            max_iterations=max_iterations
        )
        _initialized_components["iteration_engine"] = engine
        logger.info(f"Initialized iteration engine (max_iterations: {max_iterations})")
    
    return _initialized_components["iteration_engine"]


# =============================================================================
# SPRINT 4 - EXPANSIVE SAMPLE SYSTEM INITIALIZERS
# =============================================================================

def init_section_sample_mapper() -> SectionSampleMapper:
    """
    Initialize section sample mapper for 12-sample-to-sections mapping.
    
    Returns:
        SectionSampleMapper instance
    
    Raises:
        ImportError: If section_sample_mapper module is not available
    """
    if "section_sample_mapper" not in _initialized_components:
        if not _section_sample_mapper_loaded:
            raise ImportError(
                "section_sample_mapper module not available. "
                "Ensure section_sample_mapper.py is present in engines/"
            )
        
        mapper = SectionSampleMapper()
        _initialized_components["section_sample_mapper"] = mapper
        logger.info("Initialized section sample mapper")
    
    return _initialized_components["section_sample_mapper"]


def init_expansive_coherence_validator(
    metadata_store=None
) -> ExpansiveCoherenceValidator:
    """
    Initialize expansive coherence validator for 12+ sample validation.
    
    Args:
        metadata_store: Optional metadata store for sample features
    
    Returns:
        ExpansiveCoherenceValidator instance
    
    Raises:
        ImportError: If expansive_coherence_validator module is not available
    """
    if "expansive_coherence_validator" not in _initialized_components:
        if not _expansive_coherence_validator_loaded:
            raise ImportError(
                "expansive_coherence_validator module not available. "
                "Ensure expansive_coherence_validator.py is present in engines/"
            )
        
        validator = ExpansiveCoherenceValidator(metadata_store=metadata_store)
        _initialized_components["expansive_coherence_validator"] = validator
        logger.info("Initialized expansive coherence validator")
    
    return _initialized_components["expansive_coherence_validator"]


def init_multi_sample_injector(
    live_bridge=None
) -> MultiSampleInjector:
    """
    Initialize multi-sample injector for varied sample injection.
    
    Args:
        live_bridge: Optional LiveBridge instance for Ableton integration
    
    Returns:
        MultiSampleInjector instance
    
    Raises:
        ImportError: If multi_sample_injector module is not available
    """
    if "multi_sample_injector" not in _initialized_components:
        if not _multi_sample_injector_loaded:
            raise ImportError(
                "multi_sample_injector module not available. "
                "Ensure multi_sample_injector.py is present in engines/"
            )
        
        injector = MultiSampleInjector(live_bridge=live_bridge)
        _initialized_components["multi_sample_injector"] = injector
        logger.info("Initialized multi-sample injector")
    
    return _initialized_components["multi_sample_injector"]


def init_section_builder_real(
    live_bridge=None,
    micro_injector=None
) -> SectionBuilderReal:
    """
    Initialize section builder real for building sections in Ableton Live.
    
    Args:
        live_bridge: AbletonLiveBridge instance for track/clip operations
        micro_injector: MultiSampleInjector instance for sample placement
    
    Returns:
        SectionBuilderReal instance
    
    Raises:
        ImportError: If section_builder_real module is not available
    """
    if "section_builder_real" not in _initialized_components:
        if not _section_builder_real_loaded:
            raise ImportError(
                "section_builder_real module not available. "
                "Ensure section_builder_real.py is present in engines/"
            )
        
        # Initialize micro_injector if not provided
        if micro_injector is None and _multi_sample_injector_loaded:
            micro_injector = init_multi_sample_injector(live_bridge=live_bridge)
        
        builder = SectionBuilderReal(
            live_bridge=live_bridge,
            micro_injector=micro_injector
        )
        _initialized_components["section_builder_real"] = builder
        logger.info("Initialized section builder real")
    
    return _initialized_components["section_builder_real"]


def init_variation_controller() -> VariationController:
    """
    Initialize variation controller for sample variation strategies.
    
    Returns:
        VariationController instance
    
    Raises:
        ImportError: If variation_controller module is not available
    """
    if "variation_controller" not in _initialized_components:
        if not _variation_controller_loaded:
            raise ImportError(
                "variation_controller module not available. "
                "Ensure variation_controller.py is present in engines/"
            )
        
        controller = VariationController()
        _initialized_components["variation_controller"] = controller
        logger.info("Initialized variation controller")
    
    return _initialized_components["variation_controller"]


# =============================================================================
# SPRINT 5 - ADVANCED ENGINE INITIALIZERS
# =============================================================================

def init_library_indexer(library_path: str) -> LibraryIndexer:
    """
    Initialize library indexer for fast sample library indexing and search.
    
    Args:
        library_path: Path to the sample library directory
    
    Returns:
        LibraryIndexer instance
    
    Raises:
        ImportError: If library_indexer module is not available
    """
    if "library_indexer" not in _initialized_components:
        if not _library_indexer_loaded:
            raise ImportError(
                "library_indexer module not available. "
                "Ensure library_indexer.py is present in engines/"
            )
        
        indexer = LibraryIndexer(library_path=library_path)
        _initialized_components["library_indexer"] = indexer
        logger.info(f"Initialized library indexer (path: {library_path})")
    
    return _initialized_components["library_indexer"]


def init_massive_selector(library_indexer=None) -> MassiveSelector:
    """
    Initialize massive selector for selecting large sample sets (20+ per category).
    
    Args:
        library_indexer: Optional LibraryIndexer instance for sample access
    
    Returns:
        MassiveSelector instance
    
    Raises:
        ImportError: If massive_selector module is not available
    """
    if "massive_selector" not in _initialized_components:
        if not _massive_selector_loaded:
            raise ImportError(
                "massive_selector module not available. "
                "Ensure massive_selector.py is present in engines/"
            )
        
        selector = MassiveSelector(library_indexer=library_indexer)
        _initialized_components["massive_selector"] = selector
        logger.info("Initialized massive selector")
    
    return _initialized_components["massive_selector"]


def init_drum_layer_engine(live_bridge=None) -> DrumLayerEngine:
    """
    Initialize drum layer engine for multi-layer drum sound design.
    
    Args:
        live_bridge: Optional LiveBridge instance for Ableton integration
    
    Returns:
        DrumLayerEngine instance
    
    Raises:
        ImportError: If drum_layer_engine module is not available
    """
    if "drum_layer_engine" not in _initialized_components:
        if not _drum_layer_engine_loaded:
            raise ImportError(
                "drum_layer_engine module not available. "
                "Ensure drum_layer_engine.py is present in engines/"
            )
        
        engine = DrumLayerEngine(live_bridge=live_bridge)
        _initialized_components["drum_layer_engine"] = engine
        logger.info("Initialized drum layer engine")
    
    return _initialized_components["drum_layer_engine"]


def init_midi_orchestrator(library_path: str) -> MIDIOrchestrator:
    """
    Initialize MIDI orchestrator for MIDI file orchestration and arrangement.
    
    Args:
        library_path: Path to the MIDI/library directory
    
    Returns:
        MIDIOrchestrator instance
    
    Raises:
        ImportError: If midi_orchestrator module is not available
    """
    if "midi_orchestrator" not in _initialized_components:
        if not _midi_orchestrator_loaded:
            raise ImportError(
                "midi_orchestrator module not available. "
                "Ensure midi_orchestrator.py is present in engines/"
            )
        
        orchestrator = MIDIOrchestrator(library_path=library_path)
        _initialized_components["midi_orchestrator"] = orchestrator
        logger.info(f"Initialized MIDI orchestrator (path: {library_path})")
    
    return _initialized_components["midi_orchestrator"]


def init_dj_structure_engine(bpm: float = 128.0) -> DJStructureEngine:
    """
    Initialize DJ structure engine for DJ-friendly extended arrangements.
    
    Args:
        bpm: Tempo in BPM for the DJ structure (default 128.0)
    
    Returns:
        DJStructureEngine instance
    
    Raises:
        ImportError: If dj_structure_engine module is not available
    """
    if "dj_structure_engine" not in _initialized_components:
        if not _dj_structure_engine_loaded:
            raise ImportError(
                "dj_structure_engine module not available. "
                "Ensure dj_structure_engine.py is present in engines/"
            )
        
        engine = DJStructureEngine(bpm=bpm)
        _initialized_components["dj_structure_engine"] = engine
        logger.info(f"Initialized DJ structure engine (BPM: {bpm})")
    
    return _initialized_components["dj_structure_engine"]


def init_massive_injector(live_bridge=None) -> MassiveInjector:
    """
    Initialize massive injector for injecting large sample sets into Arrangement View.
    
    Args:
        live_bridge: Optional LiveBridge instance for Ableton integration
    
    Returns:
        MassiveInjector instance
    
    Raises:
        ImportError: If massive_injector module is not available
    """
    if "massive_injector" not in _initialized_components:
        if not _massive_injector_loaded:
            raise ImportError(
                "massive_injector module not available. "
                "Ensure massive_injector.py is present in engines/"
            )
        
        injector = MassiveInjector(live_bridge=live_bridge)
        _initialized_components["massive_injector"] = injector
        logger.info("Initialized massive injector")
    
    return _initialized_components["massive_injector"]


def init_advanced_automation(live_bridge=None) -> AdvancedAutomation:
    """
    Initialize advanced automation for sophisticated curves and envelopes.
    
    Args:
        live_bridge: Optional LiveBridge instance for Ableton integration
    
    Returns:
        AdvancedAutomation instance
    
    Raises:
        ImportError: If advanced_automation module is not available
    """
    if "advanced_automation" not in _initialized_components:
        if not _advanced_automation_loaded:
            raise ImportError(
                "advanced_automation module not available. "
                "Ensure advanced_automation.py is present in engines/"
            )
        
        automation = AdvancedAutomation(live_bridge=live_bridge)
        _initialized_components["advanced_automation"] = automation
        logger.info("Initialized advanced automation")
    
    return _initialized_components["advanced_automation"]


def init_ambience_generator(live_bridge=None) -> AmbienceGenerator:
    """
    Initialize ambience generator for ambient textures and atmospheres.
    
    Args:
        live_bridge: Optional LiveBridge instance for Ableton integration
    
    Returns:
        AmbienceGenerator instance
    
    Raises:
        ImportError: If ambience_generator module is not available
    """
    if "ambience_generator" not in _initialized_components:
        if not _ambience_generator_loaded:
            raise ImportError(
                "ambience_generator module not available. "
                "Ensure ambience_generator.py is present in engines/"
            )
        
        generator = AmbienceGenerator(live_bridge=live_bridge)
        _initialized_components["ambience_generator"] = generator
        logger.info("Initialized ambience generator")
    
    return _initialized_components["ambience_generator"]


# =============================================================================
# SPRINT 5.5 - ADVANCED PRODUCTION ENGINE INITIALIZERS
# =============================================================================

def init_micro_batch_injector(live_bridge=None) -> MicroBatchInjector:
    """
    Initialize micro batch injector for efficient batch sample injection.
    
    Args:
        live_bridge: Optional LiveBridge instance for Ableton integration
    
    Returns:
        MicroBatchInjector instance
    
    Raises:
        ImportError: If micro_batch_injector module is not available
    """
    if "micro_batch_injector" not in _initialized_components:
        if not _micro_batch_injector_loaded:
            raise ImportError(
                "micro_batch_injector module not available. "
                "Ensure micro_batch_injector.py is present in engines/"
            )
        
        injector = MicroBatchInjector(live_bridge=live_bridge)
        _initialized_components["micro_batch_injector"] = injector
        logger.info("Initialized micro batch injector")
    
    return _initialized_components["micro_batch_injector"]


def init_real_coherence_validator() -> RealCoherenceValidator:
    """
    Initialize real coherence validator for real-time coherence validation.
    
    Returns:
        RealCoherenceValidator instance
    
    Raises:
        ImportError: If real_coherence_validator module is not available
    """
    if "real_coherence_validator" not in _initialized_components:
        if not _real_coherence_validator_loaded:
            raise ImportError(
                "real_coherence_validator module not available. "
                "Ensure real_coherence_validator.py is present in engines/"
            )
        
        validator = RealCoherenceValidator()
        _initialized_components["real_coherence_validator"] = validator
        logger.info("Initialized real coherence validator")
    
    return _initialized_components["real_coherence_validator"]


def init_smart_sample_selector(validator=None) -> SmartSampleSelector:
    """
    Initialize smart sample selector for intelligent sample selection.
    
    Args:
        validator: Optional RealCoherenceValidator instance for validation
    
    Returns:
        SmartSampleSelector instance
    
    Raises:
        ImportError: If smart_sample_selector module is not available
    """
    if "smart_sample_selector" not in _initialized_components:
        if not _smart_sample_selector_loaded:
            raise ImportError(
                "smart_sample_selector module not available. "
                "Ensure smart_sample_selector.py is present in engines/"
            )
        
        # Initialize validator if not provided
        if validator is None and _real_coherence_validator_loaded:
            validator = init_real_coherence_validator()
        
        selector = SmartSampleSelector(validator=validator)
        _initialized_components["smart_sample_selector"] = selector
        logger.info("Initialized smart sample selector")
    
    return _initialized_components["smart_sample_selector"]


def init_realtime_progress_tracker() -> RealtimeProgressTracker:
    """
    Initialize realtime progress tracker for production progress tracking.
    
    Returns:
        RealtimeProgressTracker instance
    
    Raises:
        ImportError: If realtime_progress_tracker module is not available
    """
    if "realtime_progress_tracker" not in _initialized_components:
        if not _realtime_progress_tracker_loaded:
            raise ImportError(
                "realtime_progress_tracker module not available. "
                "Ensure realtime_progress_tracker.py is present in engines/"
            )
        
        tracker = RealtimeProgressTracker()
        _initialized_components["realtime_progress_tracker"] = tracker
        logger.info("Initialized realtime progress tracker")
    
    return _initialized_components["realtime_progress_tracker"]


def init_section_automation(live_bridge=None) -> SectionAutomation:
    """
    Initialize section automation for automated section parameter control.
    
    Args:
        live_bridge: Optional LiveBridge instance for Ableton integration
    
    Returns:
        SectionAutomation instance
    
    Raises:
        ImportError: If section_automation module is not available
    """
    if "section_automation" not in _initialized_components:
        if not _section_automation_loaded:
            raise ImportError(
                "section_automation module not available. "
                "Ensure section_automation.py is present in engines/"
            )
        
        automation = SectionAutomation(live_bridge=live_bridge)
        _initialized_components["section_automation"] = automation
        logger.info("Initialized section automation")
    
    return _initialized_components["section_automation"]


def init_export_engine(live_bridge=None) -> ExportEngine:
    """
    Initialize export engine for professional export and rendering.
    
    Args:
        live_bridge: Optional LiveBridge instance for Ableton integration
    
    Returns:
        ExportEngine instance
    
    Raises:
        ImportError: If export_engine module is not available
    """
    if "export_engine" not in _initialized_components:
        if not _export_engine_loaded:
            raise ImportError(
                "export_engine module not available. "
                "Ensure export_engine.py is present in engines/"
            )
        
        engine = ExportEngine(live_bridge=live_bridge)
        _initialized_components["export_engine"] = engine
        logger.info("Initialized export engine")
    
    return _initialized_components["export_engine"]


def init_master_orchestrator_sprint55(
    live_bridge=None,
    progress_tracker=None
) -> MasterOrchestratorSprint55:
    """
    Initialize master orchestrator Sprint 5.5 for central production orchestration.
    
    Args:
        live_bridge: Optional LiveBridge instance for Ableton integration
        progress_tracker: Optional RealtimeProgressTracker instance for progress tracking
    
    Returns:
        MasterOrchestratorSprint55 instance
    
    Raises:
        ImportError: If master_orchestrator_sprint55 module is not available
    """
    if "master_orchestrator_sprint55" not in _initialized_components:
        if not _master_orchestrator_sprint55_loaded:
            raise ImportError(
                "master_orchestrator_sprint55 module not available. "
                "Ensure master_orchestrator_sprint55.py is present in engines/"
            )
        
        # Initialize progress_tracker if not provided
        if progress_tracker is None and _realtime_progress_tracker_loaded:
            progress_tracker = init_realtime_progress_tracker()
        
        orchestrator = MasterOrchestratorSprint55(
            live_bridge=live_bridge,
            progress_tracker=progress_tracker
        )
        _initialized_components["master_orchestrator_sprint55"] = orchestrator
        logger.info("Initialized master orchestrator Sprint 5.5")
    
    return _initialized_components["master_orchestrator_sprint55"]


def clear_initialized_components():
    """Clear all initialized component singletons. Useful for testing."""
    _initialized_components.clear()
    logger.info("Cleared all initialized component singletons")


# =============================================================================
# CONFIGURATION DETECTION
# =============================================================================

def get_system_capabilities() -> Dict[str, Any]:
    """
    Detect available capabilities (numpy, librosa, etc.).
    
    Returns a dictionary indicating what's available in the current
    Python environment. This is used to auto-configure engines.
    
    Returns:
        Dict with keys:
            - numpy: bool - numpy available
            - librosa: bool - librosa available
            - sqlite3: bool - sqlite3 available
            - python_version: str - Python version
            - modules: Dict[str, str] - status of each engine module
            - has_advanced_analysis: bool - can do audio analysis
            - has_metadata_db: bool - can use metadata database
    """
    capabilities = {
        "numpy": False,
        "librosa": False,
        "sqlite3": False,
        "python_version": f"{sys.version_info.major}.{sys.version_info.minor}.{sys.version_info.micro}",
        "modules": {},
        "has_advanced_analysis": False,
        "has_metadata_db": False,
    }
    
    # Check numpy
    try:
        import numpy
        capabilities["numpy"] = True
        capabilities["numpy_version"] = numpy.__version__
    except ImportError:
        pass
    
    # Check librosa
    try:
        import librosa
        capabilities["librosa"] = True
        capabilities["librosa_version"] = librosa.__version__
        capabilities["has_advanced_analysis"] = True
    except ImportError:
        pass
    
    # Check sqlite3
    try:
        import sqlite3
        capabilities["sqlite3"] = True
        capabilities["has_metadata_db"] = True
    except ImportError:
        pass
    
    # Check all engine modules
    for name, status in _module_availability.items():
        capabilities["modules"][name] = status.value
    
    # Check for new components specifically
    new_components = [
        "metadata_store",
        "abstract_analyzer", 
        "arrangement_recorder",
        "live_bridge"
    ]
    for component in new_components:
        if component not in capabilities["modules"]:
            capabilities["modules"][component] = "not_loaded"
    
    # Check for Senior Architecture - Intelligent Selection System components
    intelligent_selection_components = [
        "intelligent_selector",
        "coherence_scorer",
        "variation_engine",
        "rationale_logger",
        "preset_manager",
        "iteration_engine"
    ]
    for component in intelligent_selection_components:
        if component not in capabilities["modules"]:
            capabilities["modules"][component] = "not_loaded"
    
    # Intelligent Selection System ready if all components available
    capabilities["has_intelligent_selection"] = all(
        capabilities["modules"].get(c) == "available"
        for c in intelligent_selection_components
    )
    
    return capabilities


def configure_engines_for_capabilities():
    """
    Auto-configure engines based on available dependencies.
    
    This function sets up the engine configuration to work optimally
    with whatever dependencies are available. Call this at startup
    to ensure engines are properly configured.
    
    Side effects:
        - Sets global configuration flags
        - Logs configuration decisions
        - May initialize singletons if needed
    """
    capabilities = get_system_capabilities()
    
    logger.info("Configuring engines for system capabilities...")
    logger.info(f"Python version: {capabilities['python_version']}")
    logger.info(f"Numpy: {capabilities['numpy']}")
    logger.info(f"Librosa: {capabilities['librosa']}")
    logger.info(f"SQLite3: {capabilities['sqlite3']}")
    
    # Configure based on available modules
    if capabilities["has_advanced_analysis"]:
        logger.info("Advanced analysis available - enabling full audio processing")
        # Could set global flags here
    else:
        logger.warning("Advanced analysis not available - using database-only mode")
    
    if capabilities["has_metadata_db"]:
        logger.info("Metadata database available")
        # Could auto-initialize metadata store here
    
    # Log module availability
    available = [name for name, status in capabilities["modules"].items() 
                 if status == "available"]
    missing = [name for name, status in capabilities["modules"].items() 
               if status == "missing"]
    
    logger.info(f"Available modules: {', '.join(available)}")
    if missing:
        logger.warning(f"Missing modules: {', '.join(missing)}")
    
    return capabilities


# =============================================================================
# COMPATIBILITY LAYER
# =============================================================================

def get_analyzer(prefer_database: bool = True) -> FeatureExtractor:
    """
    Get appropriate analyzer based on configuration.
    
    This function provides a compatibility layer that returns the best
    available analyzer for the current system configuration.
    
    Priority order:
    1. HybridExtractor (if available) - best of both worlds
    2. DatabaseExtractor (if prefer_database and available) - fast metadata
    3. LibrosaExtractor (if available) - full audio analysis
    4. Basic placeholder - raises errors on use
    
    Args:
        prefer_database: If True, prefer database-only extraction when
                        hybrid is not available
    
    Returns:
        FeatureExtractor instance appropriate for the system
    
    Raises:
        ImportError: If no analyzer can be created
    """
    # Try hybrid first (best option)
    if _abstract_analyzer_loaded:
        try:
            return init_hybrid_extractor()
        except Exception as e:
            logger.warning(f"Could not initialize hybrid extractor: {e}")
    
    # Try database-only
    if prefer_database and _metadata_store_loaded:
        try:
            store = init_metadata_store()
            return DatabaseExtractor(store)
        except Exception as e:
            logger.warning(f"Could not initialize database extractor: {e}")
    
    # Try librosa-only
    if _abstract_analyzer_loaded:
        try:
            return LibrosaExtractor()
        except Exception as e:
            logger.warning(f"Could not initialize librosa extractor: {e}")
    
    # Nothing available - create placeholder that gives helpful errors
    logger.error("No analyzer available - returning placeholder")
    return FeatureExtractor()  # This will raise NotImplementedError on use


def get_recorder_or_placeholder(song=None, connection=None):
    """
    Get arrangement recorder if available, or a placeholder.
    
    This is a compatibility function for code that needs to work
    whether or not the arrangement_recorder is available.
    
    Args:
        song: Ableton Live song object (optional)
        connection: TCP connection (optional)
    
    Returns:
        ArrangementRecorder or RecordingState stub
    """
    if _arrangement_recorder_loaded and song is not None and connection is not None:
        return init_arrangement_recorder(song, connection)
    
    # Return a stub that has the state property
    class RecordingStub:
        state = RecordingState.IDLE
        def is_available(self): return False
    
    return RecordingStub()


# =============================================================================
# PUBLIC API - __all__ DEFINITION
# =============================================================================

__all__ = [
    # =========================================================================
    # NEW COMPONENTS (Metadata & Analysis)
    # =========================================================================
    # Metadata Store
    "SampleMetadataStore",
    "SampleFeatures",
    # Abstract Analyzer
    "FeatureExtractor",
    "LibrosaExtractor",
    "DatabaseExtractor",
    "HybridExtractor",
    # Arrangement Recording
    "ArrangementRecorder",
    "RecordingState",
    "RecordingConfig",
    # Live Bridge
    "AbletonLiveBridge",
    # Parameter Discovery (Agent 9)
    "ParameterDiscovery",
    "DeviceParameter",
    "DeviceInfo",
    "discover_parameters",
    "match_parameter",
    
    # =========================================================================
    # SENIOR ARCHITECTURE - INTELLIGENT SELECTION SYSTEM
    # =========================================================================
    # Intelligent Selector
    "IntelligentSampleSelector",
    "CoherenceError",
    "select_coherent_kit",
    # Coherence Scorer
    "CoherenceScorer",
    "score_kit_coherence",
    "is_professional_grade",
    "MIN_COHERENCE",
    # Variation Engine
    "VariationEngine",
    "SECTION_PROFILES",
    "evolve_kit_for_section",
    "find_energy_variant",
    # Rationale Logger
    "RationaleLogger",
    "log_sample_selection",
    "log_kit_assembly",
    "get_session_rationale",
    # Preset Manager
    "PresetManager",
    "KitPreset",
    "save_kit_preset",
    "load_kit_preset",
    "list_presets",
    # Iteration Engine
    "IterationEngine",
    "ProfessionalCoherenceError",
    "CoherenceScorer",
    "RationaleLogger",
    "IterationResult",
    "IterationAttempt",
    "IterationStatus",
    "ITERATION_STRATEGIES",
    "iterate_for_coherence",
    "quick_coherence_check",
    
    # =========================================================================
    # AGENTE 12 - VST/AU Plugin Support
    # =========================================================================
    "VSTManager",
    "PluginInfo",
    "PluginType",
    "PluginCategory",
    "ParameterInfo",
    "get_vst_manager",
    "scan_vst_plugins",
    "get_vst_presets",
    "get_all_plugins",
    "validate_plugin",
    "get_plugin_parameters",
    
    # =========================================================================
    # SENIOR ARCHITECTURE - NEW MODULES (Coherence System, Audio Analyzer Dual, Bus Architecture)
    # =========================================================================
    # Coherence System
    "calculate_joint_score",
    "update_cross_generation_memory",
    "get_cross_generation_penalty",
    "get_persistent_fatigue",
    "ROLE_ACTIVITY",
    "SECTION_DENSITY_PROFILES",
    "get_section_role_bonus",
    "calculate_section_appropriateness",
    "set_palette_lock",
    "calculate_palette_bonus",
    "get_palette_coherence_score",
    "calculate_comprehensive_coherence",
    "reset_all_memory",
    "get_coherence_memory_stats",
    # Audio Analyzer Dual
    "AudioAnalyzerDual",
    "AudioFeatures",
    "analyze_sample",
    "analyze_audio",
    "get_backend_info",
    # Bus Architecture
    "BUS_GAIN_CALIBRATION",
    "RETURN_CONFIG",
    "ROLE_MIX",
    "MASTER_CHAIN",
    "BusArchitecture",
    "create_bus_track",
    "create_return_track",
    "route_track_to_bus",
    "set_track_send",
    "configure_bus_gain",
    "configure_return_effect",
    "apply_role_mix",
    "configure_master_chain",
    "apply_professional_mix",
    "get_bus_config",
    "get_return_config",
    "get_role_mix",
    "list_available_buses",
    "list_available_returns",
    "list_available_roles",
    
    # =========================================================================
    # INITIALIZATION FUNCTIONS
    # =========================================================================
    "init_metadata_store",
    "init_hybrid_extractor",
    "init_arrangement_recorder",
    "init_live_bridge",
    "init_intelligent_selector",
    "init_coherence_scorer",
    "init_variation_engine",
    "init_rationale_logger",
    "init_preset_manager",
    "init_iteration_engine",
    "init_section_sample_mapper",
    "init_expansive_coherence_validator",
    "init_multi_sample_injector",
    "init_variation_controller",
    "init_library_indexer",
    "init_massive_selector",
    "init_drum_layer_engine",
    "init_midi_orchestrator",
    "init_dj_structure_engine",
    "init_massive_injector",
    "init_advanced_automation",
    "init_ambience_generator",
    "clear_initialized_components",
    
    # =========================================================================
    # CONFIGURATION & COMPATIBILITY
    # =========================================================================
    "get_system_capabilities",
    "configure_engines_for_capabilities",
    "get_analyzer",
    "get_recorder_or_placeholder",
    "is_module_available",
    "ModuleAvailability",
    
    # =========================================================================
    # SPRINT 1 - Core Analysis
    # =========================================================================
    "LibreriaAnalyzer",
    "analyze_library",
    "EmbeddingEngine",
    "create_embeddings_index",
    "find_similar_samples",
    "find_samples_like_audio",
    "ReferenceMatcher",
    "SpectralFingerprint",
    "SampleMatch",
    "UserSoundProfile",
    "AudioAnalyzer",
    "SimilarityEngine",
    "get_matcher",
    "get_user_profile",
    "get_recommended_samples",
    "analyze_reference",
    "refresh_profile",
    "SampleSelector",
    "SampleInfo",
    "DrumKit",
    "InstrumentGroup",
    "get_selector",
    "select_samples_for_track",
    "get_drum_kit",
    "reset_cross_generation_memory",
    
    # =========================================================================
    # SPRINT 2 - Pattern & Mixing
    # Sprint 7: Added ChordProgressionsPro (16 progresiones con tensión)
    # =========================================================================
    "DembowPatterns",
    "BassPatterns",
    "ChordProgressions",
    "ChordProgressionsPro",
    "MelodyGenerator",
    "HumanFeel",
    "PercussionLibrary",
    "NoteEvent",
    "ScaleType",
    "get_patterns",
    "ReggaetonGenerator",
    "SongGenerator",
    "SongConfig",
    "Section",
    "TrackConfig",
    "ClipConfig",
    "Pattern",
    "DeviceConfig",
    "get_song_generator",
    "generate_song",
    "generate_from_reference",
    "get_supported_styles",
    "get_supported_structures",
    "MixingEngine",
    "BusManager",
    "ReturnTrackManager",
    "MixConfiguration",
    "get_mixing_engine",
    "reset_mixing_engine",
    "DeviceManager",
    "EQConfiguration",
    "CompressionSettings",
    "GainStaging",
    "MasterChain",
    "DeviceParameter",
    "MixQualityChecker",
    "DeviceInfo",
    "QualityReport",
    "SUPPORTED_DEVICES",
    "EQ_PRESETS",
    "COMP_PRESETS",
    "MASTER_PRESETS",
    "get_device_manager",
    "get_eq_configuration",
    "get_compression_settings",
    "get_gain_staging",
    "get_master_chain",
    "get_device_parameter",
    "get_quality_checker",
    "create_standard_buses",
    "apply_send_preset",
    "ProductionWorkflow",
    "ActionHistory",
    "ProjectValidator",
    "ExportManager",
    "ActionRecord",
    "ValidationIssue",
    "get_workflow",
    
    # =========================================================================
    # SPRINT 4 - Expansive Sample System (12 Samples per Category)
    # =========================================================================
    "SectionSampleMapper",
    "SectionConfig",
    "ExpansiveCoherenceValidator",
    "MultiSampleInjector",
    "InjectionPlan",
    "VariationController",
    "RotationMode",
    "VariationConfig",
    "init_section_sample_mapper",
    "init_expansive_coherence_validator",
    "init_multi_sample_injector",
    "init_variation_controller",
    "select_expansive_kit",
    
    # Section Builder Real - Real-time section building
    "SectionBuilderReal",
    "SectionBuildReport",
    "create_section_builder",
    "init_section_builder_real",
    
    # =========================================================================
    # SPRINT 5 - Advanced Engines (Library Indexing, MIDI Orchestration, DJ Structure)
    # =========================================================================
    "LibraryIndexer",
    "MassiveSelector",
    "DrumLayerEngine",
    "MIDIOrchestrator",
    "DJStructureEngine",
    "MassiveInjector",
    "AdvancedAutomation",
    "AmbienceGenerator",
    "init_library_indexer",
    "init_massive_selector",
    "init_drum_layer_engine",
    "init_midi_orchestrator",
    "init_dj_structure_engine",
    "init_massive_injector",
    "init_advanced_automation",
    "init_ambience_generator",
    
    # =========================================================================
    # SPRINT 5.5 - Advanced Production Engines (Micro-Batch, Real-Time, Export)
    # =========================================================================
    # Micro Batch Injector
    "MicroBatchInjector",
    "BatchInjectionPlan",
    "init_micro_batch_injector",
    # Real Coherence Validator
    "RealCoherenceValidator",
    "ValidationResult",
    "init_real_coherence_validator",
    # Smart Sample Selector
    "SmartSampleSelector",
    "SelectionCriteria",
    "init_smart_sample_selector",
    # Realtime Progress Tracker
    "RealtimeProgressTracker",
    "ProgressStage",
    "init_realtime_progress_tracker",
    # Section Automation
    "SectionAutomation",
    "init_section_automation",
    # Export Engine
    "ExportEngine",
    "ExportConfig",
    "RenderFormat",
    "init_export_engine",
    # Master Orchestrator Sprint 5.5
    "MasterOrchestratorSprint55",
    "OrchestrationConfig",
    "ProductionStage",
    "init_master_orchestrator_sprint55",
    
    # =========================================================================
    # SPRINT 3 - Arrangement & Harmony
    # =========================================================================
    "ArrangementBuilder",
    "AutomationEngine",
    "FXCreator",
    "SampleProcessor",
    "ArrangementConfig",
    "SectionMarker",
    "AutomationPoint",
    "AutomationEnvelope",
    "ArrangementClip",
    "ArrangementSection",
    "arrangement_to_dict",
    "dict_to_arrangement",
    "get_arrangement_length",
    "create_full_arrangement",
    "ProjectAnalyzer",
    "CounterMelodyGenerator",
    "SampleIntelligence",
    
    # VariationEngine (Sample-based, from variation_engine module)
    # Note: This is the sample kit evolution engine. For MIDI variations,
    # use the methods from harmony_engine module directly.
    "VariationEngine",
    "SectionKit",
    "EnergyCharacteristics",
    "CoherenceMetrics",
    "SECTION_PROFILES",
    "evolve_kit_for_sections",
    "get_section_energy_profile",
    "validate_coherence",
    
    "PresetManager",
    "Preset",
    "TrackPreset",
    "MixingConfig",
    "SampleSelectionCriteria",
    "get_preset_manager",
    "apply_preset_to_project",
    "get_default_preset",
    "list_available_presets",
    "quick_apply_preset",
    "create_builtin_presets",
    
    # =========================================================================
    # FASES 6-9: Session Orchestrator + Warp Automation + Full MIDI Orchestration
    # =========================================================================
    # BPM Analyzer
    "BPMAnalyzer",
    "analyze_sample",
    "init_bpm_analyzer",
    "get_bpm_analyzer",
    # Spectral Coherence
    "SpectralCoherence",
    "get_sample_similarity",
    "init_spectral_coherence",
    "get_spectral_coherence",
    # Session Orchestrator
    "SessionOrchestrator",
    "validate_and_fix_track",
    "init_session_orchestrator",
    "get_session_orchestrator",
    
    # =========================================================================
    # SESSION VALIDATOR - Comprehensive Session View Validation
    # =========================================================================
    "SessionValidator",
    "validate_session_production",
]


# =============================================================================
# MODULE INITIALIZATION
# =============================================================================

def _on_import():
    """Run on module import to set up the package."""
    # Detect capabilities but don't configure yet (let caller decide)
    capabilities = get_system_capabilities()
    
    # Log summary
    available_count = sum(1 for s in capabilities["modules"].values() if s == "available")
    total_count = len(capabilities["modules"])
    
    logger.debug(
        f"Engines package loaded. "
        f"Capabilities: numpy={capabilities['numpy']}, "
        f"librosa={capabilities['librosa']}, "
        f"modules={available_count}/{total_count} available"
    )

# Run initialization
_on_import()
