from pydantic_ai.models import Model, infer_model
from pydantic_ai.models.fallback import FallbackModel

from app.models.google import build_google_model
from app.settings import Settings


def is_google(model_str: str) -> bool:
    return model_str.startswith(("google", "gemini"))


def get_model_name(model_str: str) -> str:
    return model_str.split(":", 1)[1] if ":" in model_str else model_str


def build_primary_model(settings: Settings) -> Model:
    primary = settings.models.primary_model

    if is_google(primary):
        return build_google_model(get_model_name(primary))

    return infer_model(primary)


def build_primary_smart_model(settings: Settings) -> Model:
    primary = settings.models.primary_smart_model

    if not primary:
        raise ValueError("Primary smart model is not defined in settings.")

    if is_google(primary):
        return build_google_model(get_model_name(primary))

    return infer_model(primary)


def build_model(settings: Settings) -> Model:
    primary = build_primary_model(settings)
    fallback = settings.models.fallback_model

    if fallback and is_google(fallback):
        fallback = build_google_model(get_model_name(fallback))

    return FallbackModel(primary, fallback) if fallback else primary


def build_smart_model(settings: Settings) -> Model:
    if not settings.models.primary_smart_model:
        return build_model(settings)

    primary = build_primary_smart_model(settings)
    fallback = settings.models.fallback_smart_model

    if fallback and is_google(fallback):
        fallback = build_google_model(get_model_name(fallback))

    return FallbackModel(primary, fallback) if fallback else primary
