"""
系统管理对外API接口
提供给外部系统调用的API接口
"""
import sys
import os
import logging
from datetime import datetime, timezone

# 添加src目录到Python路径
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '../../../..'))

from fastapi import APIRouter, Depends, HTTPException
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
from app.services.jwt_token import verify_token
from app.schemas.base import ApiResponse
from app.services.system_service import SystemService

# 获取logger
logger = logging.getLogger(__name__)

router = APIRouter(prefix="/system", tags=["系统管理对外API"])
security = HTTPBearer()


@router.get("/role/user_list/{role_code}")
async def get_user_list_by_role(
    role_code: str,
    credentials: HTTPAuthorizationCredentials = Depends(security)
):
    """
    根据角色标识查询用户列表
    
    Args:
        role_code: 角色标识编码，如：label_admin(标注管理员), labeler(标注员)
        credentials: Bearer Token认证
    
    Returns:
        用户列表，包含用户ID、用户名、邮箱、电话
    """
    try:
        # 验证令牌
        payload = verify_token(credentials.credentials)
        if not payload:
            return ApiResponse(
                code="200002",
                message="令牌失效",
                timestamp=datetime.now(timezone.utc).isoformat()
            ).model_dump()
        
        # 验证角色标识参数
        if not role_code or not role_code.strip():
            return ApiResponse(
                code="100001",
                message="角色标识不能为空",
                timestamp=datetime.now(timezone.utc).isoformat()
            ).model_dump()
        
        # 调用 service 层获取用户列表
        system_service = SystemService()
        success, data, message = await system_service.get_user_list_by_role_code(role_code.strip())
        
        if success:
            return ApiResponse(
                code="000000",
                message="成功",
                data=data,
                timestamp=datetime.now(timezone.utc).isoformat()
            ).model_dump()
        else:
            # 根据错误消息返回相应的错误码
            if "不存在" in message:
                code = "300001"  # 应用不存在（这里用于角色不存在）
            else:
                code = "500001"  # 服务器内部错误
            
            return ApiResponse(
                code=code,
                message=message,
                timestamp=datetime.now(timezone.utc).isoformat()
            ).model_dump()
        
    except Exception as e:
        logger.exception(f"根据角色标识查询用户列表错误: role_code={role_code}")
        return ApiResponse(
            code="500001",
            message="服务器内部错误",
            timestamp=datetime.now(timezone.utc).isoformat()
        ).model_dump()
