"""REST API routes for Local LLM service integration."""
from __future__ import annotations

import logging
from fastapi import APIRouter, HTTPException, Query
from pydantic import BaseModel

from prompt_auto_lab.core.model_clients import fetch_local_models

router = APIRouter(prefix="/api/local", tags=["local"])
logger = logging.getLogger(__name__)


class LocalModelInfo(BaseModel):
    """Information about an available local model."""
    id: str
    name: str
    vendor: str
    family: str
    version: str
    max_input_tokens: int | None = None
    supports_image_to_text: bool = False
    supports_tool_calling: bool = False


class LocalModelsResponse(BaseModel):
    """Response containing available local models."""
    models: list[LocalModelInfo]
    endpoint: str


@router.get("/models", response_model=LocalModelsResponse)
async def get_models(
    endpoint: str = Query(
        default="http://localhost:23333",
        description="Base URL of the local LLM service"
    )
) -> LocalModelsResponse:
    """Fetch available models from a local LLM service.

    Args:
        endpoint: The base URL of the local service (default: http://localhost:23333).

    Returns:
        List of available models with their capabilities.

    Raises:
        HTTPException: If the local service is unreachable or returns an error.
    """
    try:
        raw_models = await fetch_local_models(base_url=endpoint)

        models = []
        for m in raw_models:
            capabilities = m.get("capabilities", {})
            models.append(LocalModelInfo(
                id=m.get("id", ""),
                name=m.get("name", m.get("id", "")),
                vendor=m.get("vendor", "local"),
                family=m.get("family", ""),
                version=m.get("version", ""),
                max_input_tokens=m.get("maxInputTokens"),
                supports_image_to_text=capabilities.get("supportsImageToText", False),
                supports_tool_calling=capabilities.get("supportsToolCalling", False),
            ))

        return LocalModelsResponse(models=models, endpoint=endpoint)

    except Exception as e:
        logger.warning("Failed to fetch local models from %s: %s", endpoint, e)
        raise HTTPException(
            status_code=503,
            detail=f"Failed to connect to local LLM service at {endpoint}: {e}"
        )
