"""
文本对话接口（文字面试模式）
"""
from fastapi import APIRouter, HTTPException
from loguru import logger

from app.schemas import ApiResponse, ChatRequest, ChatResponse
from app.services.coze_service import coze_service

router = APIRouter()


@router.post("/chat", response_model=ApiResponse)
async def chat(request: ChatRequest):
    """
    文本对话（文字面试模式）
    
    使用 /v3/chat API 与 Chatflow 对话。
    session_id 通过 user_id 传递，工作流从 USER_INPUT 获取。
    """
    try:
        logger.info(f"Chat request: session_id={request.sessionId}, conv_id={request.conversationId}, message={request.message[:50]}...")
        
        # 使用 /v3/chat API（Chatflow 对话）
        # session_id 作为 user_id 传递，工作流从 {{USER_INPUT}} 获取
        result = await coze_service.chat(
            message=request.message,
            user_id=request.sessionId,  # session_id 作为 user_id
            conversation_id=request.conversationId,
        )
        
        response_data = ChatResponse(
            reply=result.get("reply", ""),
            conversationId=result.get("conversation_id", ""),
            debugInfo=result.get("debug_info"),
        )
        
        logger.info(f"Chat response: {response_data.reply[:50] if response_data.reply else 'empty'}...")
        
        return ApiResponse(
            code=0,
            message="success",
            data=response_data
        )
        
    except Exception as e:
        logger.error(f"Chat error: {e}")
        raise HTTPException(status_code=500, detail=str(e))
