import httpx from typing import Optional from app.config import settings import logging logger = logging.getLogger(__name__) class JavaClient: """Java 后端 HTTP 客户端 (所有 Python→Java 通信的单一入口)""" def __init__(self): self.base_url = settings.java_base_url self._client: Optional[httpx.AsyncClient] = None async def _get_client(self) -> httpx.AsyncClient: if self._client is None: self._client = httpx.AsyncClient( base_url=self.base_url, timeout=httpx.Timeout(10.0, connect=3.0), ) return self._client async def close(self): if self._client: await self._client.aclose() self._client = None async def get_published_articles(self) -> list[dict]: """获取已发布的文章列表 (用于构建知识库)""" client = await self._get_client() resp = await client.post("/api/article/list", json={"status": "published", "limit": 1000}) data = resp.json() if data.get("code") == 200: return data.get("data", []) return [] async def search_products(self, keyword: str, limit: int = 5) -> list[dict]: """按关键词搜索上架商品""" client = await self._get_client() resp = await client.post("/api/product/search", json={ "keyword": keyword, "status": "上架", "limit": limit }) data = resp.json() if data.get("code") == 200: return data.get("data", []) return [] async def search_activities(self, keyword: str, limit: int = 5) -> list[dict]: """按关键词搜索进行中的活动""" client = await self._get_client() resp = await client.post("/api/activity/search", json={ "keyword": keyword, "status": "published", "limit": limit }) data = resp.json() if data.get("code") == 200: return data.get("data", []) return [] async def search_articles(self, keyword: str, limit: int = 5) -> list[dict]: """按关键词搜索已发布文章""" client = await self._get_client() resp = await client.post("/api/article/search", json={ "keyword": keyword, "status": "published", "limit": limit }) data = resp.json() if data.get("code") == 200: return data.get("data", []) return [] async def get_user_context(self, user_id: int, params: Optional[dict] = None) -> dict: """获取用户上下文 (对应 Java AiContextService)""" client = await self._get_client() resp = await client.post(settings.effective_java_context_url, json={ "user_id": str(user_id), "params": params or {}, }) data = resp.json() if data.get("code") == 200: return data.get("data", {}) return {}