from typing import Any, List

from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session

from app.core.security import get_current_user
from app.db.session import get_db
from app.models.user import User
from app.schemas.model_config import (
    ModelConfigCreate,
    ModelConfigResponse,
    ModelConfigUpdate,
    ModelProviderOptionsResponse,
)
from app.services.model_config import ModelConfigService, provider_options_response

router = APIRouter()


@router.get("/providers", response_model=ModelProviderOptionsResponse)
def read_model_provider_options(
    current_user: User = Depends(get_current_user),
) -> Any:
    _ = current_user
    return provider_options_response()


@router.get("", response_model=List[ModelConfigResponse])
def read_model_configs(
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user),
) -> Any:
    return ModelConfigService.list_configs(db, current_user.id)


@router.post("", response_model=ModelConfigResponse)
def create_model_config(
    *,
    db: Session = Depends(get_db),
    payload: ModelConfigCreate,
    current_user: User = Depends(get_current_user),
) -> Any:
    try:
        return ModelConfigService.create_config(db, current_user.id, payload)
    except ValueError as exc:
        raise HTTPException(status_code=400, detail=str(exc)) from exc


@router.put("/{config_id}", response_model=ModelConfigResponse)
def update_model_config(
    *,
    db: Session = Depends(get_db),
    config_id: int,
    payload: ModelConfigUpdate,
    current_user: User = Depends(get_current_user),
) -> Any:
    item = ModelConfigService.get_config(db, current_user.id, config_id)
    if not item:
        raise HTTPException(status_code=404, detail="Model config not found.")
    try:
        return ModelConfigService.update_config(db, item, payload)
    except ValueError as exc:
        raise HTTPException(status_code=400, detail=str(exc)) from exc


@router.delete("/{config_id}", response_model=ModelConfigResponse)
def delete_model_config(
    *,
    db: Session = Depends(get_db),
    config_id: int,
    current_user: User = Depends(get_current_user),
) -> Any:
    item = ModelConfigService.get_config(db, current_user.id, config_id)
    if not item:
        raise HTTPException(status_code=404, detail="Model config not found.")
    response = ModelConfigResponse.model_validate(item)
    ModelConfigService.delete_config(db, item)
    return response
