"""Compatibility helpers for migrating legacy eval.py files."""

from __future__ import annotations

from typing import TYPE_CHECKING, Any


if TYPE_CHECKING:
    from collections.abc import Callable, Mapping


def make_legacy_split_evaluator(
    legacy_get_metrics: Callable[..., Any],
    *,
    model: Any,
    index_to_labels: Mapping[str, str],
    runtime_framework: str | None = None,
    action_tracker: Any | None = None,
    **extra_kwargs: Any,
) -> Callable[[str, object], Any]:
    """Wrap legacy ``get_metrics`` function into split-callback signature.

    Args:
        legacy_get_metrics: Legacy evaluator callable from older projects.
        model: Loaded model object passed through to legacy evaluator.
        index_to_labels: Mapping of class index to label names.
        runtime_framework: Optional runtime name forwarded to legacy evaluator.
        action_tracker: Optional tracker object forwarded to legacy evaluator.
        **extra_kwargs: Additional keyword arguments forwarded to evaluator.

    Returns:
        Callable with signature ``fn(split, loader) -> payload``.
    """

    def _evaluate_split(split: str, loader: object) -> Any:
        """Invoke the legacy evaluator using split and loader inputs.

        Args:
            split: Dataset split name (for example ``train`` or ``val``).
            loader: Dataloader-like object passed through to legacy code.

        Returns:
            Legacy evaluator output payload for the requested split.
        """
        kwargs: dict[str, Any] = dict(extra_kwargs)
        if runtime_framework is not None:
            kwargs["runtime_framework"] = runtime_framework
        if action_tracker is not None:
            return legacy_get_metrics(split, loader, model, index_to_labels, action_tracker, **kwargs)
        return legacy_get_metrics(split, loader, model, index_to_labels, **kwargs)

    return _evaluate_split


def ensure_metric_functions(metric_functions: Mapping[str, Any]) -> dict[str, Any]:
    """Ensure required metric function keys exist with safe defaults.

    Args:
        metric_functions: Existing metric function mapping from caller.

    Returns:
        Normalized mapping containing all formatter-required keys.
    """
    normalized = dict(metric_functions)
    normalized.setdefault("accuracy_per_class", lambda _output, _target: {})
    return normalized

