"""Runtime resolution helpers for deploy routing."""

from __future__ import annotations

from typing import Any


_RUNTIME_ALIASES = {
    "pt": "pytorch",
    "pytorch": "pytorch",
    "torch": "pytorch",
    "torch_script": "torchscript",
    "torchscript": "torchscript",
    "onnx": "onnx",
    "openvino": "openvino",
    "trt": "tensorrt",
    "tensor_rt": "tensorrt",
    "tensorrt": "tensorrt",
}


def normalize_runtime(runtime_framework: str | None, *, default: str = "pytorch") -> str:
    """Normalize runtime labels to canonical deploy route keys.

    Args:
        runtime_framework: Runtime label to normalize, or ``None``.
        default: Fallback runtime key when input is empty.

    Returns:
        Canonical lowercase runtime key.
    """
    if not runtime_framework:
        return default
    key = runtime_framework.strip().lower()
    return _RUNTIME_ALIASES.get(key, key)


def resolve_runtime_framework(action_tracker: Any, *, default: str = "pytorch") -> str:
    """Resolve runtime from ActionTracker-compatible metadata locations.

    Args:
        action_tracker: Tracker-like object carrying runtime metadata.
        default: Runtime key used when no explicit runtime is found.

    Returns:
        Canonical runtime key resolved from tracker metadata.
    """
    # ResNet-style field
    export_format = getattr(action_tracker, "export_format", None)
    if isinstance(export_format, str) and export_format.strip():
        return normalize_runtime(export_format, default=default)

    # Common backend payload
    action_details = getattr(action_tracker, "action_details", None)
    if isinstance(action_details, dict):
        runtime_framework = action_details.get("runtimeFramework")
        if isinstance(runtime_framework, str) and runtime_framework.strip():
            return normalize_runtime(runtime_framework, default=default)

    # Optional job params fallback
    get_job_params = getattr(action_tracker, "get_job_params", None)
    if callable(get_job_params):
        try:
            job_params = get_job_params() or {}
        except Exception:
            job_params = {}
        if isinstance(job_params, dict):
            runtime_framework = job_params.get("runtimeFramework")
            if isinstance(runtime_framework, str) and runtime_framework.strip():
                return normalize_runtime(runtime_framework, default=default)

    return normalize_runtime(default, default=default)
