"""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 a split callback signature.

    The returned callable matches: ``fn(split, loader) -> payload``.
    """

    def _evaluate_split(split: str, loader: object) -> Any:
        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 formatter-required keys exist with safe defaults."""
    normalized = dict(metric_functions)
    normalized.setdefault("accuracy_per_class", lambda _output, _target: {})
    return normalized

