from fastapi import APIRouter, BackgroundTasks, Depends
import uuid

from app.core.deps import get_current_user
from app.core.response import success_response

from .schemas import GenerateRequest
from .task_store import create_task, get_task, list_tasks
from .workflow import process_video_generation, get_lipsync_health, get_voiceclone_health
from .service import list_generated_videos, delete_generated_video


router = APIRouter()


@router.post("/generate")
async def generate_video(
    req: GenerateRequest,
    background_tasks: BackgroundTasks,
    current_user: dict = Depends(get_current_user)
):
    user_id = current_user["id"]
    task_id = str(uuid.uuid4())
    create_task(task_id, user_id)
    background_tasks.add_task(process_video_generation, task_id, req, user_id)
    return success_response({"task_id": task_id})


@router.get("/tasks/{task_id}")
async def get_task_status(task_id: str, current_user: dict = Depends(get_current_user)):
    task = get_task(task_id)
    # 验证任务归属：只能查看自己的任务
    if task.get("status") != "not_found" and task.get("user_id") != current_user["id"]:
        return success_response({"status": "not_found"})
    return success_response(task)


@router.get("/tasks")
async def list_tasks_view(current_user: dict = Depends(get_current_user)):
    # 只返回当前用户的任务
    all_tasks = list_tasks()
    user_tasks = [t for t in all_tasks if t.get("user_id") == current_user["id"]]
    return success_response({"tasks": user_tasks})


@router.get("/lipsync/health")
async def lipsync_health():
    return success_response(await get_lipsync_health())


@router.get("/voiceclone/health")
async def voiceclone_health():
    return success_response(await get_voiceclone_health())


@router.get("/generated")
async def list_generated(current_user: dict = Depends(get_current_user)):
    return success_response(await list_generated_videos(current_user["id"]))


@router.delete("/generated/{video_id}")
async def delete_generated(video_id: str, current_user: dict = Depends(get_current_user)):
    result = await delete_generated_video(current_user["id"], video_id)
    return success_response(result, message="视频已删除")
