"""参考音频管理 API"""
from fastapi import APIRouter, UploadFile, File, Form, HTTPException, Depends
from loguru import logger

from app.core.deps import get_current_user
from app.core.response import success_response
from app.modules.ref_audios.schemas import RenameRequest
from app.modules.ref_audios import service

router = APIRouter()


@router.post("")
async def upload_ref_audio(
    file: UploadFile = File(...),
    ref_text: str = Form(""),
    user: dict = Depends(get_current_user)
):
    """上传参考音频"""
    try:
        result = await service.upload_ref_audio(file, ref_text, user["id"])
        return success_response(result)
    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)}")


@router.get("")
async def list_ref_audios(user: dict = Depends(get_current_user)):
    """列出当前用户的所有参考音频"""
    try:
        result = await service.list_ref_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_ref_audio(audio_id: str, user: dict = Depends(get_current_user)):
    """删除参考音频"""
    try:
        await service.delete_ref_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_ref_audio(
    audio_id: str,
    request: RenameRequest,
    user: dict = Depends(get_current_user)
):
    """重命名参考音频"""
    try:
        result = await service.rename_ref_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)}")


@router.post("/{audio_id:path}/retranscribe")
async def retranscribe_ref_audio(
    audio_id: str,
    user: dict = Depends(get_current_user)
):
    """重新识别参考音频的文字内容"""
    try:
        result = await service.retranscribe_ref_audio(audio_id, 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)}")
