from fastapi import APIRouter, UploadFile, File, Form, HTTPException
from typing import Optional
import traceback
from loguru import logger

from app.core.response import success_response
from app.modules.tools import service

router = APIRouter()


@router.post("/extract-script")
async def extract_script_tool(
    file: Optional[UploadFile] = File(None),
    url: Optional[str] = Form(None),
    rewrite: bool = Form(True),
    custom_prompt: Optional[str] = Form(None)
):
    """独立文案提取工具"""
    try:
        result = await service.extract_script(file=file, url=url, rewrite=rewrite, custom_prompt=custom_prompt)
        return success_response(result)
    except ValueError as e:
        raise HTTPException(400, str(e))
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"Tool extract failed: {e}")
        logger.error(traceback.format_exc())
        msg = str(e)
        if "Fresh cookies" in msg:
            msg = "下载失败：目标平台开启了反爬验证，请过段时间重试或直接上传视频文件。"
        raise HTTPException(500, f"提取失败: {msg}")
