from typing import List, Optional

from ..base import get_models as g_get_models, Model
from .protocol import ModelItem, ModelResponse
from .helpers import create_404_error, create_500_error

def to_model_id(model: Model) -> str:
    """Convert a Model object to a string ID."""
    return model.get('id', '').lower().replace(' ', '-')

def get_models(
    before_id: Optional[str] = None,
    after_id: Optional[str] = None,
    limit: int = 100,
) -> ModelResponse:
    try:
        g_models = g_get_models()
        model_list: List[ModelItem] = []
        for model in g_models:
            model_list.append(ModelItem(
                id=to_model_id(model),
                type='model',
                display_name=model.get('id', ''),
            ))
        if before_id or after_id:
            model_list.sort(key=lambda x: x.id)
            if before_id:
                model_list = [m for m in model_list if m.id < before_id]
            if after_id:
                model_list = [m for m in model_list if m.id > after_id]
        if limit > 0:
            model_list = model_list[:limit]
        return ModelResponse(
            data=model_list,
            first_id=model_list[0].id if model_list else None,
            last_id=model_list[-1].id if model_list else None,
            has_more=len(g_models) > len(model_list),
        )
    except Exception as e:
        return create_500_error(str(e))

def get_model(model_id: str) -> ModelItem:
    try:
        g_models = g_get_models()
        for model in g_models:
            if to_model_id(model) == model_id:
                return ModelItem(
                    id=to_model_id(model),
                    type='model',
                    display_name=model.get('id', ''),
                )
        return create_404_error(f'model {model_id} not found')
    except Exception as e:
        return create_500_error(str(e))
