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

from app.services.eval_service import EvalService
from app.utils.response import success_response

router = APIRouter()
service = EvalService()


class EvalRequest(BaseModel):
    model_id: int
    package_id: int


@router.get('/packages')
def list_packages(
    category_id: str = Query(default=''),
    name: str = Query(default=''),
):
    return success_response(data=service.list_packages(category_id=category_id, name=name.strip()))


@router.get('/models')
def list_models():
    return success_response(data=service.list_saved_models())


@router.get('/records')
def list_records():
    return success_response(data=service.list_records())


@router.get('/records/{record_id}')
def get_record(record_id: int):
    try:
        return success_response(data=service.get_record(record_id))
    except ValueError as error:
        raise HTTPException(status_code=404, detail=str(error)) from error


@router.delete('/records/{record_id}')
def delete_record(record_id: int):
    try:
        service.delete_record(record_id)
        return success_response(data=True, message='评估记录已删除')
    except ValueError as error:
        raise HTTPException(status_code=404, detail=str(error)) from error


@router.post('/run')
def run_evaluation(request: EvalRequest):
    try:
        result = service.evaluate(model_id=request.model_id, package_id=request.package_id)
        return success_response(data=result, message='评估完成')
    except ValueError as error:
        raise HTTPException(status_code=400, detail=str(error)) from error
