"""Dispatcher module for language handler access."""

from __future__ import annotations

from enum import Enum
from typing import TYPE_CHECKING

from core.errors import HandlerNotImplementedError
from core.registry import registry

if TYPE_CHECKING:
    from core.protocols import LanguageHandler


class Feature(Enum):
    """Supported language handler features and their capability flags."""

    TESTGEN = "supports_testgen"
    OPTIMIZER = "supports_optimizer"
    CODE_REPAIR = "supports_code_repair"
    JIT_REWRITE = "supports_jit_rewrite"
    OPTIMIZATION_REVIEW = "supports_optimization_review"
    EXPLANATIONS = "supports_explanations"


def get_handler_for_language(language_id: str) -> LanguageHandler:
    """Get a handler instance for a specific language."""
    handler_class = registry.get_handler(language_id)
    return handler_class()


def get_handler_for_feature(language_id: str, feature: str) -> LanguageHandler:
    """Get a handler instance for a specific language and feature combination."""
    handler_class = registry.get_handler(language_id)

    try:
        feat = Feature[feature.upper()]
    except KeyError:
        valid = [f.name.lower() for f in Feature]
        msg = f"Unknown feature: {feature}. Valid features: {valid}"
        raise ValueError(msg) from None

    if not getattr(handler_class, feat.value, False):
        raise HandlerNotImplementedError(language_id=language_id, feature=feature, capability=feat.value)

    return handler_class()
