"""生成配音 API"""
from fastapi import APIRouter, BackgroundTasks, Depends, HTTPException
import uuid
from loguru import logger

from app.core.deps import get_current_user
from app.core.response import success_response
from app.modules.videos.task_store import create_task, get_task
from app.modules.generated_audios.schemas import GenerateAudioRequest, RenameAudioRequest
from app.modules.generated_audios import service

router = APIRouter()


@router.post("/generate")
async def generate_audio(
    req: GenerateAudioRequest,
    background_tasks: BackgroundTasks,
    user: dict = Depends(get_current_user),
):
    """异步生成配音（返回 task_id）"""
    task_id = str(uuid.uuid4())
    create_task(task_id, user["id"])
    background_tasks.add_task(service.generate_audio_task, task_id, req, user["id"])
    return success_response({"task_id": task_id})


@router.get("/tasks/{task_id}")
async def get_audio_task(task_id: str, user: dict = Depends(get_current_user)):
    """轮询配音生成进度"""
    task = get_task(task_id)
    if task.get("status") != "not_found" and task.get("user_id") != user["id"]:
        return success_response({"status": "not_found"})
    return success_response(task)


@router.get("")
async def list_audios(user: dict = Depends(get_current_user)):
    """列出当前用户所有已生成配音"""
    try:
        result = await service.list_generated_audios(user["id"])
        return success_response(result)
    except Exception as e:
        logger.error(f"列出配音失败: {e}")
        raise HTTPException(status_code=500, detail=f"获取列表失败: {str(e)}")


@router.delete("/{audio_id:path}")
async def delete_audio(audio_id: str, user: dict = Depends(get_current_user)):
    """删除配音"""
    try:
        await service.delete_generated_audio(audio_id, user["id"])
        return success_response(message="删除成功")
    except PermissionError as e:
        raise HTTPException(status_code=403, detail=str(e))
    except Exception as e:
        logger.error(f"删除配音失败: {e}")
        raise HTTPException(status_code=500, detail=f"删除失败: {str(e)}")


@router.put("/{audio_id:path}")
async def rename_audio(
    audio_id: str,
    request: RenameAudioRequest,
    user: dict = Depends(get_current_user),
):
    """重命名配音"""
    try:
        result = await service.rename_generated_audio(audio_id, request.new_name, user["id"])
        return success_response(result, message="重命名成功")
    except PermissionError as e:
        raise HTTPException(status_code=403, detail=str(e))
    except ValueError as e:
        raise HTTPException(status_code=400, detail=str(e))
    except Exception as e:
        logger.error(f"重命名配音失败: {e}")
        raise HTTPException(status_code=500, detail=f"重命名失败: {str(e)}")
