import httpx
from typing import Optional, Dict, Any
from pathlib import Path
from backend.config import config


class DossierAIClient:
    """卷宗系统dossierai服务客户端"""
    
    def __init__(
        self, 
        base_url: Optional[str] = None,
        timeout: Optional[int] = None
    ):
        self.base_url = base_url or config.dossierai_base_url
        self.timeout = timeout or config.dossierai_timeout
        self._client: Optional[httpx.AsyncClient] = None
    
    async def _get_client(self) -> httpx.AsyncClient:
        """获取或创建异步客户端"""
        if self._client is None:
            self._client = httpx.AsyncClient(timeout=self.timeout)
        return self._client
    
    async def close(self):
        """关闭客户端"""
        if self._client:
            await self._client.aclose()
            self._client = None
    
    async def parse_document(self, file_path: str) -> Dict[str, Any]:
        """
        文档解析/OCR
        API: POST /document/parse
        支持：PDF、图片、文档等
        """
        client = await self._get_client()
        
        with open(file_path, 'rb') as f:
            files = {'file': (Path(file_path).name, f)}
            response = await client.post(
                f"{self.base_url}/document/parse",
                files=files
            )
        
        if response.status_code != 200:
            raise Exception(f"DossierAI parse failed: {response.text}")
        
        return response.json()
    
    async def recognize_intent(self, text: str) -> Dict[str, Any]:
        """
        意图识别
        API: POST /intent/recognize
        识别：BUG vs 功能需求
        """
        client = await self._get_client()
        
        response = await client.post(
            f"{self.base_url}/intent/recognize",
            json={"text": text}
        )
        
        if response.status_code != 200:
            raise Exception(f"DossierAI intent recognition failed: {response.text}")
        
        return response.json()
    
    async def chat(self, message: str, context: Optional[str] = None) -> str:
        """
        AI聊天
        API: POST /message/chat
        用于复杂内容的理解
        """
        client = await self._get_client()
        
        payload = {"message": message}
        if context:
            payload["context"] = context
        
        response = await client.post(
            f"{self.base_url}/message/chat",
            json=payload
        )
        
        if response.status_code != 200:
            raise Exception(f"DossierAI chat failed: {response.text}")
        
        return response.json().get("response", "")
    
    async def health_check(self) -> bool:
        """检查dossierai服务是否可用"""
        try:
            client = await self._get_client()
            response = await client.get(f"{self.base_url}/health")
            return response.status_code == 200
        except Exception:
            return False
    
    async def is_available(self) -> bool:
        """检查服务是否可用（带fallback）"""
        try:
            return await self.health_check()
        except Exception:
            return False


# 全局客户端实例
_dossierai_client: Optional[DossierAIClient] = None


def get_dossierai_client() -> DossierAIClient:
    """获取DossierAI客户端单例"""
    global _dossierai_client
    if _dossierai_client is None:
        _dossierai_client = DossierAIClient()
    return _dossierai_client
