"""模型管理 API"""

from typing import List

from fastapi import APIRouter, HTTPException, UploadFile

from ..models.schemas import Live2DModel
from ..services.config_service import ConfigService

router = APIRouter(prefix="/models", tags=["模型管理"])

# 全局配置服务实例
config_service: ConfigService = None


def init_config_service(service: ConfigService):
    """初始化配置服务"""
    global config_service
    config_service = service


# ============================================================================
# Live2D 模型管理
# ============================================================================


@router.get("/live2d", response_model=List[Live2DModel], summary="获取所有 Live2D 模型")
async def get_live2d_models():
    """获取所有 Live2D 模型配置"""
    return await config_service.get_live2d_models()


@router.post("/live2d", response_model=Live2DModel, summary="添加 Live2D 模型")
async def add_live2d_model(model: Live2DModel):
    """添加或更新 Live2D 模型配置"""
    return await config_service.add_live2d_model(model)


@router.delete("/live2d/{model_id}", summary="删除 Live2D 模型")
async def delete_live2d_model(model_id: str):
    """删除指定的 Live2D 模型"""
    success = await config_service.delete_live2d_model(model_id)
    if not success:
        raise HTTPException(status_code=404, detail=f"模型不存在: {model_id}")
    return {"message": f"模型 {model_id} 已删除"}


@router.post("/live2d/upload", summary="上传 Live2D 模型文件")
async def upload_live2d_model(file: UploadFile):
    """上传 Live2D 模型文件（.model3.json）"""
    # TODO: 实现文件上传逻辑
    # 1. 验证文件类型
    # 2. 保存到 models 目录
    # 3. 自动添加到配置
    return {"message": "文件上传功能待实现", "filename": file.filename}
