"""
言迹智能工牌API接口
"""

import logging
from typing import List

from fastapi import APIRouter, Depends, Query

from app.core.deps import get_current_user
from app.models.user import User
from app.schemas.base import ResponseModel
from app.schemas.yanji import (
    GetConversationsByVisitIdsResponse,
    GetConversationsResponse,
    YanjiConversation,
)
from app.services.yanji_service import YanjiService

logger = logging.getLogger(__name__)

router = APIRouter()


@router.post("/conversations/by-visit-ids", response_model=ResponseModel[GetConversationsByVisitIdsResponse])
async def get_conversations_by_visit_ids(
    external_visit_ids: List[str] = Query(
        ...,
        min_length=1,
        max_length=10,
        description="三方来访单ID列表（最多10个）",
    ),
    current_user: User = Depends(get_current_user),
):
    """
    根据来访单ID获取对话记录（ASR转写文字）
    
    这是获取对话记录的主要接口，适用于：
    1. 已知来访单ID的场景
    2. 获取特定对话记录用于AI评分
    3. 批量获取多个对话记录
    """
    try:
        yanji_service = YanjiService()
        conversations = await yanji_service.get_conversations_by_visit_ids(
            external_visit_ids=external_visit_ids
        )

        return ResponseModel(
            code=200,
            message="获取成功",
            data=GetConversationsByVisitIdsResponse(
                conversations=conversations, total=len(conversations)
            ),
        )

    except Exception as e:
        logger.error(f"获取对话记录失败: {e}", exc_info=True)
        return ResponseModel(code=500, message=f"获取失败: {str(e)}", data=None)


@router.get("/conversations", response_model=ResponseModel[GetConversationsResponse])
async def get_employee_conversations(
    consultant_phone: str = Query(..., description="员工手机号"),
    limit: int = Query(10, ge=1, le=100, description="获取数量"),
    current_user: User = Depends(get_current_user),
):
    """
    获取员工最近的对话记录
    
    注意：目前此接口功能有限，因为言迹API没有直接通过员工手机号查询录音的接口。
    推荐使用 /conversations/by-visit-ids 接口。
    
    后续可扩展：
    1. 先查询员工的来访单列表
    2. 再获取这些来访单的对话记录
    """
    try:
        yanji_service = YanjiService()
        conversations = await yanji_service.get_recent_conversations(
            consultant_phone=consultant_phone, limit=limit
        )

        return ResponseModel(
            code=200,
            message="获取成功",
            data=GetConversationsResponse(
                conversations=conversations, total=len(conversations)
            ),
        )

    except Exception as e:
        logger.error(f"获取员工对话记录失败: {e}", exc_info=True)
        return ResponseModel(code=500, message=f"获取失败: {str(e)}", data=None)


@router.get("/test-auth")
async def test_yanji_auth(current_user: User = Depends(get_current_user)):
    """
    测试言迹API认证
    
    用于验证OAuth2.0认证是否正常工作
    """
    try:
        yanji_service = YanjiService()
        access_token = await yanji_service.get_access_token()

        return ResponseModel(
            code=200,
            message="认证成功",
            data={
                "access_token": access_token[:20] + "...",  # 只显示前20个字符
                "base_url": yanji_service.base_url,
            },
        )

    except Exception as e:
        logger.error(f"言迹API认证失败: {e}", exc_info=True)
        return ResponseModel(code=500, message=f"认证失败: {str(e)}", data=None)

