"""
候选人相关接口
"""
import time
import uuid
from fastapi import APIRouter, UploadFile, File, Form, HTTPException
from loguru import logger

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

router = APIRouter()


def generate_session_id(name: str) -> str:
    """生成会话 ID"""
    timestamp = int(time.time())
    random_code = uuid.uuid4().hex[:6]
    return f"SESS_{timestamp}_{name}_{random_code}"


@router.post("/candidates", response_model=ApiResponse)
async def submit_candidate(
    name: str = Form(..., min_length=2, max_length=20, description="候选人姓名"),
    resume: UploadFile = File(..., description="简历文件"),
):
    """
    提交候选人信息（上传简历）
    
    - 上传简历到 Coze
    - 生成 session_id
    - 返回 session_id 和 file_id
    """
    try:
        # 验证文件类型
        allowed_types = [
            "application/pdf",
            "application/msword",
            "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
        ]
        if resume.content_type not in allowed_types:
            raise HTTPException(
                status_code=400,
                detail="只支持 PDF、DOC、DOCX 格式的文件"
            )
        
        # 验证文件大小（10MB）
        content = await resume.read()
        if len(content) > 10 * 1024 * 1024:
            raise HTTPException(
                status_code=400,
                detail="文件大小不能超过 10MB"
            )
        
        # 上传文件到 Coze
        file_result = await coze_service.upload_file(content, resume.filename or "resume.pdf")
        file_id = file_result.get("id")
        
        if not file_id:
            raise HTTPException(
                status_code=500,
                detail="文件上传失败"
            )
        
        # 生成 session_id
        session_id = generate_session_id(name)
        
        logger.info(f"Candidate submitted: name={name}, session_id={session_id}, file_id={file_id}")
        
        return ApiResponse(
            code=0,
            message="success",
            data=SubmitCandidateResponse(
                sessionId=session_id,
                fileId=file_id,
            )
        )
        
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"Submit candidate error: {e}")
        raise HTTPException(status_code=500, detail=str(e))
