"""
面试初始化接口
"""
from fastapi import APIRouter, UploadFile, File, Form, HTTPException
from loguru import logger

from app.schemas import ApiResponse
from app.services.coze_service import coze_service

router = APIRouter()


@router.post("/init-interview", response_model=ApiResponse)
async def init_interview(
    name: str = Form(..., description="候选人姓名"),
    file: UploadFile = File(..., description="简历文件（PDF）"),
):
    """
    初始化面试
    
    1. 上传简历到 Coze
    2. 获取文件临时 URL
    3. 调用工作流 A（解析简历、创建记录）
    4. 返回 session_id
    
    后续使用 session_id 创建语音房间进行面试
    """
    try:
        # 验证文件类型
        if not file.filename.lower().endswith('.pdf'):
            raise HTTPException(status_code=400, detail="仅支持 PDF 格式")
        
        # 读取文件内容
        content = await file.read()
        
        # 验证文件大小（最大 10MB）
        if len(content) > 10 * 1024 * 1024:
            raise HTTPException(status_code=400, detail="文件大小不能超过 10MB")
        
        logger.info(f"Init interview: name={name}, file={file.filename}, size={len(content)} bytes")
        
        # 执行完整的初始化流程（返回详细调试信息）
        result = await coze_service.init_interview(
            name=name,
            file_content=content,
            filename=file.filename,
        )
        
        session_id = result.get("session_id", "")
        debug_info = result.get("debug_info", {})
        
        logger.info(f"Interview initialized: session_id={session_id}")
        logger.info(f"Debug info: {debug_info}")
        
        return ApiResponse(
            code=0,
            message="success",
            data={
                "sessionId": session_id,
                "name": name,
                "debugInfo": debug_info,
            }
        )
        
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"Init interview error: {e}")
        raise HTTPException(status_code=500, detail=str(e))
