import os
import logging
import httpx
from typing import Optional, Dict, Any

logger = logging.getLogger("cs_agent")

class DispatchService:
    """
    8006 即时派发服务 API 接入 (正式对齐版)
    """
    
    def __init__(self):
        # 严格按照老大提供的最新对齐信息
        self.base_url = "http://1.12.50.92:8006"
        self.api_key = "tuhui_dispatch_key_2026"
        self.timeout = 10.0

    async def assign_designer(self) -> Optional[str]:
        """
        调用 /assign 接口，一键获取当前可用的设计师名字
        """
        url = f"{self.base_url}/assign"
        # 严格使用 X-API-Key 请求头和带下划线的 Key
        headers = {"X-API-Key": self.api_key}
        
        try:
            async with httpx.AsyncClient(timeout=self.timeout) as client:
                response = await client.get(url, headers=headers)
                
                if response.status_code == 200:
                    data = response.json()
                    if data.get("success"):
                        designer = data.get("assigned_to")
                        logger.info(f"[Dispatch] 派单成功！设计师: {designer}")
                        return designer
                    else:
                        logger.warning(f"[Dispatch] 派单被拒: {data.get('reason')}")
                elif response.status_code == 401:
                    logger.error(f"[Dispatch] 授权失败(401)！请检查 Key 是否为: {self.api_key}")
                else:
                    logger.error(f"[Dispatch] API 异常，状态码: {response.status_code}")
        except Exception as e:
            logger.error(f"[Dispatch] 网络请求崩溃: {e}")
        
        return None

# 全局单例
dispatch_service = DispatchService()
