from __future__ import annotations

from typing import Dict, Tuple

from keiro.gateway.infra.model_alias import ModelAlias, resolve_model_alias
from ember.models.providers import resolve_model_id


def resolve_model_metadata(model: str) -> Tuple[str, str, Dict[str, str]]:
    """Return (provider_hint, canonical_model, provider_overrides)."""
    alias = resolve_model_alias(model)
    if alias is not None:
        canonical = _alias_canonical_model(alias)
        provider_overrides = dict(alias.provider_models or {})
        return alias.provider, canonical, provider_overrides

    provider, resolved = resolve_model_id(model)
    if provider in {"takumi", "eb1", "keiro"} and model.lower().startswith("takumi/"):
        # Do not redirect takumi/<suffix> to other providers; require explicit alias
        suffix = model.split("/", 1)[1]
        aliased_suffix = resolve_model_alias(suffix)
        if aliased_suffix is not None:
            canonical = _alias_canonical_model(aliased_suffix)
            overrides = dict(aliased_suffix.provider_models or {})
            return aliased_suffix.provider, canonical, overrides
        return provider, model, {}
    return provider, resolved, {}


def _alias_canonical_model(alias: ModelAlias) -> str:
    if alias.provider_models:
        return alias.provider_models.get(alias.provider, alias.canonical_model)
    return alias.canonical_model
