"""
AI换脸API接口
提供RESTful API接口，支持换脸、历史记录查询等功能
"""

import os
import uvicorn
from pydantic import BaseModel, Field
from datetime import datetime, timedelta
from typing import Optional, List, Dict, Any, Union
from starlette.responses import FileResponse
from sqlalchemy import func, and_
from fastapi.responses import JSONResponse
from fastapi.middleware.cors import CORSMiddleware
from fastapi.staticfiles import StaticFiles
from fastapi import FastAPI, HTTPException, Depends, UploadFile, File, Form, Body, APIRouter

from backend.services.ai_swap_face_service import AISwapFaceService, process_swap_face_with_record
from backend.modules.database.operations import DatabaseOperations
from backend.utils.logger_config import setup_logger
from backend.api.auth_api import router as auth_router
from backend.api.user_material_api import router as user_material_router
from backend.api.user_template_api import router as user_template_router
from backend.modules.database.models import ProcessRecord
from backend.api.auto_post_api import router as auto_post_router

logger = setup_logger(__name__)

router = APIRouter()

# 创建服务实例
ai_swap_face_service = AISwapFaceService()
db_ops = DatabaseOperations()

# 启动任务队列服务
from backend.services.task_queue_service import get_task_queue_service
task_queue_service = get_task_queue_service()
task_queue_service.start()

# ==================== 数据模型 ====================

class SwapFaceRequest(BaseModel):
    user_id: int = Field(..., description="用户ID")
    raw_image_id: int = Field(..., description="原始图片ID")
    face_image_id: int = Field(..., description="人脸图片ID")
    quantity: Optional[int] = Field(1, ge=1, le=10, description="每组生成数量")
    
    
class SwapFaceResponse(BaseModel):
    success: bool
    task_id: Optional[str] = None
    process_record_id: Optional[int] = None
    result_image_id: Optional[int] = None
    copywriter_text: Optional[str] = None
    history_prompt: Optional[str] = None
    error: Optional[str] = None
    error_type: Optional[str] = None

# ==================== 中间件和依赖 ====================

async def verify_user(user_id: int):
    """验证用户是否存在且有效"""
    user = db_ops.get_user_by_id(user_id)
    if not user:
        raise HTTPException(status_code=404, detail=f"用户ID {user_id} 不存在")
    if not user.get("is_active", False):
        raise HTTPException(status_code=403, detail="用户账户已被禁用")
    return user

# ==================== API路由 ====================
@router.post("/api/v1/swap-face", response_model=SwapFaceResponse, tags=["AI换脸"])
async def process_swap_face(request: SwapFaceRequest):
    """
    执行AI换脸（异步任务）
    
    - **user_id**: 用户ID
    - **raw_image_id**: 原始图片ID
    - **face_image_id**: 人脸图片ID
    - **quantity**: 每组生成数量
    """
    try:
        # 验证用户
        await verify_user(request.user_id)

        # 提交任务到队列（非阻塞）
        task_id = ai_swap_face_service.submit_swap_face_task(
            user_id=request.user_id,
            raw_image_id=request.raw_image_id,
            face_image_id=request.face_image_id,
            quantity=request.quantity or 1
        )

        logger.info(f"用户 {request.user_id} 换脸任务已提交，任务ID: {task_id}")
        return SwapFaceResponse(
            success=True,
            task_id=task_id,
            process_record_id=None,
            result_image_id=None,
            copywriter_text=None,
            history_prompt=None
        )

    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"AI换脸API处理异常: {str(e)}", exc_info=True)
        raise HTTPException(status_code=500, detail=str(e))