from __future__ import annotations from typing import Any import httpx from yuxi.channels.models import HealthStatus from yuxi.utils.datetime_utils import utc_now_naive from yuxi.utils.logging_config import logger def _safe_json(resp: httpx.Response) -> dict: content_type = resp.headers.get("content-type", "") if "application/json" not in content_type and not content_type: text = resp.text[:200] logger.warning(f"[WeChat/Probe] Non-JSON response: {text}") return {} try: return resp.json() except Exception: logger.warning(f"[WeChat/Probe] JSON parse failed: {resp.text[:200]}") return {} async def probe_wecom(http_client: httpx.AsyncClient, config: dict[str, Any]) -> HealthStatus: try: token = await _get_wecom_token(http_client, config) if token: return HealthStatus( status="healthy", metadata={"mode": "wecom", "token_valid": True}, last_connected_at=utc_now_naive(), ) return HealthStatus(status="unhealthy", last_error="Failed to obtain access_token") except Exception as e: return HealthStatus(status="unhealthy", last_error=str(e)) async def probe_mp(http_client: httpx.AsyncClient, config: dict[str, Any]) -> HealthStatus: try: token = await _get_mp_token(http_client, config) if token: return HealthStatus( status="healthy", metadata={"mode": "mp", "token_valid": True}, last_connected_at=utc_now_naive(), ) return HealthStatus(status="unhealthy", last_error="Failed to obtain access_token") except Exception as e: return HealthStatus(status="unhealthy", last_error=str(e)) async def probe_bridge(http_client: httpx.AsyncClient, bridge_url: str) -> HealthStatus: try: resp = await http_client.get(f"{bridge_url}/health", timeout=5.0) if resp.status_code == 200: login_status = await _check_bridge_login(http_client, bridge_url) return HealthStatus( status="healthy", metadata={ "mode": "personal", "bridge_url": bridge_url, "logged_in": login_status.get("logged_in", False), }, last_connected_at=utc_now_naive(), ) return HealthStatus(status="degraded", last_error=f"Bridge health check returned {resp.status_code}") except Exception as e: return HealthStatus(status="unhealthy", last_error=str(e)) async def _get_wecom_token(http_client: httpx.AsyncClient, config: dict[str, Any]) -> str | None: url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken" params = { "corpid": config["corp_id"], "corpsecret": config["corp_secret"], } resp = await http_client.get(url, params=params, timeout=10.0) data = _safe_json(resp) return data.get("access_token") async def _get_mp_token(http_client: httpx.AsyncClient, config: dict[str, Any]) -> str | None: url = "https://api.weixin.qq.com/cgi-bin/token" params = { "grant_type": "client_credential", "appid": config["app_id"], "secret": config["app_secret"], } resp = await http_client.get(url, params=params, timeout=10.0) data = _safe_json(resp) return data.get("access_token") async def _check_bridge_login(http_client: httpx.AsyncClient, bridge_url: str) -> dict: try: resp = await http_client.get(f"{bridge_url}/login/status", timeout=5.0) return _safe_json(resp) except Exception: return {"logged_in": False}