"""Consolidation engine selection strategy."""

from __future__ import annotations

import logging
from typing import Any

from neurovault.cognitive.consolidation import ConsolidationEngine
from neurovault.cognitive.consolidation_v2 import ConsolidationEngineV2
from neurovault.cognitive.consolidation_v3 import ConsolidationEngineV3

logger = logging.getLogger(__name__)


class ConsolidationStrategy:
    """Select and instantiate the most appropriate consolidation engine."""

    @staticmethod
    def build(
        storage: Any,
        chronos_bridge: Any,
        extractor: Any,
        config: Any,
    ) -> ConsolidationEngine:
        consolidation_cfg = getattr(config, "consolidation", {}) or {}
        llm_cfg = getattr(config, "llm", {}) or {}
        llm_enabled = bool(consolidation_cfg.get("llm_enabled", False) or llm_cfg.get("enabled", False))
        requested = str(consolidation_cfg.get("version", "v2")).strip().lower()

        if not llm_enabled:
            return ConsolidationEngine(storage, chronos_bridge, extractor)

        constructors = {
            "v1": ConsolidationEngine,
            "1": ConsolidationEngine,
            "0.1": ConsolidationEngine,
            "v2": ConsolidationEngineV2,
            "2": ConsolidationEngineV2,
            "0.2": ConsolidationEngineV2,
            "v3": ConsolidationEngineV3,
            "3": ConsolidationEngineV3,
            "0.3": ConsolidationEngineV3,
        }

        fallback_order = ["v3", "v2", "v1"]
        if requested in constructors:
            ordered = [requested] + [v for v in fallback_order if v != requested]
        else:
            ordered = fallback_order

        for version in ordered:
            constructor = constructors[version]
            try:
                return constructor(storage, chronos_bridge, extractor)
            except Exception as exc:
                logger.debug("Consolidation engine %s unavailable: %s", version, exc)

        logger.warning("All consolidation engines failed; using baseline fallback")
        return ConsolidationEngine(storage, chronos_bridge, extractor)

