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 db.database import get_db
from entity.scene import Scene, SceneCreate, SceneUpdate, SceneInfo
from entity.scene import SceneInfo
from services.scene_service import SceneService


router = APIRouter()


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


@router.get("/page/", response_model=StandardResponse[PageResponse[SceneInfo]])
async def get_scene_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 = SceneService(db)

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

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


@router.post("/add", response_model=StandardResponse[SceneInfo])
async def create_scene(json_data: str = Form(..., description="JSON数据字段，内容为SceneCreate结构"),
                 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.")

    scene_data = SceneCreate.parse_raw(json_data)
    service = SceneService(db)
    scene = await service.create_scene(scene_data, file)
    return standard_response(data=scene)


@router.post("/update", response_model=StandardResponse[SceneInfo])
async def update_scene(json_data: str = Form(..., description="JSON数据字段，内容为SceneUpdate结构"),
                 file: UploadFile = File(None, description="模型文件"),
                 db: AsyncSession = Depends(get_db)):
    service = SceneService(db)
    scene_data = SceneUpdate.parse_raw(json_data)
    scene = await service.update_scene(scene_data, file)
    if not scene:
        return standard_error_response(data=scene_data, message="Scene not found")
    return standard_response(data=scene)


@router.delete("/delete", response_model=StandardResponse[int])
async def delete_scene(scene_id: int, db: AsyncSession = Depends(get_db)):
    service = SceneService(db)
    scene = await service.delete_scene(scene_id)
    if not scene:
        return standard_error_response(data=scene_id, message="Scene not found")
    return standard_response(data=scene_id)
