from typing import List, Optional

from fastapi import APIRouter, Depends, Query, UploadFile, File, Form
from sqlalchemy.ext.asyncio import AsyncSession

from apis.base import standard_response, StandardResponse, PageResponse, standard_error_response, convert_page_param
from app_instance import get_app
from db.database import get_db
from entity.model import AlgoModel, AlgoModelCreate, AlgoModelUpdate, AlgoModelInfo
from services.model_service import ModelService

router = APIRouter()
app = get_app()


def get_service():
    return app.state.model_service


@router.get("/list", response_model=StandardResponse[List[AlgoModelInfo]])
async def get_model_list(
        name: Optional[str] = None,
        remark: Optional[str] = None,
        db: AsyncSession = Depends(get_db)):
    service = ModelService(db)
    models = await service.get_model_list(name, remark)
    return standard_response(data=list(models))


@router.get("/page/", response_model=StandardResponse[PageResponse[AlgoModelInfo]])
async def get_model_page(
        name: Optional[str] = None,
        remark: Optional[str] = None,
        offset: int = Query(0, ge=0),  # 从第几页开始
        limit: int = Query(10, ge=1),  # 每页显示多少条记录
        db: AsyncSession = Depends(get_db)):
    service = ModelService(db)

    # 获取分页后的设备列表和总数
    offset, limit = convert_page_param(offset, limit)
    models, total = await service.get_model_page(name, remark, offset, limit)

    return standard_response(
        data=PageResponse(total=total, items=models)
    )


@router.post("/add", response_model=StandardResponse[AlgoModelInfo])
async def create_model(json_data: str = Form(..., description="JSON数据字段，内容为AlgoModelCreate结构"),
                 file: UploadFile = File(..., description="模型文件"),
                 db: AsyncSession = Depends(get_db),
                 ):
    # 检查文件类型
    if not file.filename.endswith(".zip"):
        return standard_error_response(code=500, message="Only .zip files are allowed.")

    model_data = AlgoModelCreate.parse_raw(json_data)
    service = ModelService(db)
    model = await service.create_model(model_data, file)
    return standard_response(data=model)


@router.post("/update", response_model=StandardResponse[AlgoModelInfo])
async def update_model(json_data: str = Form(..., description="JSON数据字段，内容为AlgoModelUpdate结构"),
                 file: UploadFile = File(None, description="模型文件"),
                 service: ModelService = Depends(get_service)):
    model_data = AlgoModelUpdate.parse_raw(json_data)
    model = await service.update_model(model_data, file)
    if not model:
        return standard_error_response(data=model_data, message="Model not found")
    return standard_response(data=model)


@router.delete("/delete", response_model=StandardResponse[int])
async def delete_model(model_id: int, db: AsyncSession = Depends(get_db)):
    service = ModelService(db)
    model = await service.delete_model(model_id)
    if not model:
        return standard_error_response(data=model_id, message="Model not found")
    return standard_response(data=model_id)
