"""
AI 相关 API 路由
"""

from typing import Optional

from fastapi import APIRouter, HTTPException
from pydantic import BaseModel
from loguru import logger

from app.services.glm_service import glm_service
from app.core.response import success_response


router = APIRouter(prefix="/api/ai", tags=["AI"])


class GenerateMetaRequest(BaseModel):
    """生成标题标签请求"""
    text: str


class GenerateMetaResponse(BaseModel):
    """生成标题标签响应"""
    title: str
    secondary_title: str = ""
    tags: list[str]


class RewriteRequest(BaseModel):
    """改写请求"""
    text: str
    custom_prompt: Optional[str] = None


class TranslateRequest(BaseModel):
    """翻译请求"""
    text: str
    target_lang: str


@router.post("/translate")
async def translate_text(req: TranslateRequest):
    """
    AI 翻译文案

    将文案翻译为指定目标语言
    """
    if not req.text or not req.text.strip():
        raise HTTPException(status_code=400, detail="文案不能为空")
    if not req.target_lang or not req.target_lang.strip():
        raise HTTPException(status_code=400, detail="目标语言不能为空")

    try:
        logger.info(f"Translating text to {req.target_lang}: {req.text[:50]}...")
        translated = await glm_service.translate_text(req.text.strip(), req.target_lang.strip())
        return success_response({"translated_text": translated})
    except Exception as e:
        logger.error(f"Translate failed: {e}")
        raise HTTPException(status_code=500, detail=str(e))


@router.post("/generate-meta")
async def generate_meta(req: GenerateMetaRequest):
    """
    AI 生成视频标题和标签

    根据口播文案自动生成吸引人的标题和相关标签
    """
    if not req.text or not req.text.strip():
        raise HTTPException(status_code=400, detail="口播文案不能为空")

    try:
        logger.info(f"Generating meta for text: {req.text[:50]}...")
        result = await glm_service.generate_title_tags(req.text)
        return success_response(GenerateMetaResponse(
            title=result.get("title", ""),
            secondary_title=result.get("secondary_title", ""),
            tags=result.get("tags", [])
        ).model_dump())
    except Exception as e:
        logger.error(f"Generate meta failed: {e}")
        raise HTTPException(status_code=500, detail=str(e))


@router.post("/rewrite")
async def rewrite_script(req: RewriteRequest):
    """AI 改写文案"""
    if not req.text or not req.text.strip():
        raise HTTPException(status_code=400, detail="文案不能为空")

    try:
        logger.info(f"Rewriting text: {req.text[:50]}...")
        rewritten = await glm_service.rewrite_script(req.text.strip(), req.custom_prompt)
        return success_response({"rewritten_text": rewritten})
    except Exception as e:
        logger.error(f"Rewrite failed: {e}")
        raise HTTPException(status_code=500, detail=str(e))
