import os
from datetime import datetime
from typing import Any, Dict, Optional


async def post_tianwang_callback_flow(client, event: str, data: dict, extra: Optional[Dict[str, Any]] = None):
    """将消息处理事件回调给天网。"""
    if not client._tianwang_callback_url:
        return
    try:
        import httpx

        trust_env = os.getenv("TIANWANG_CALLBACK_TRUST_ENV", "false").lower() in ("1", "true", "yes")
        payload = {
            "event": event,
            "timestamp": datetime.now().isoformat(),
            "agent_name": client._tianwang_agent_name,
            "acc_id": str(data.get("acc_id", "") or ""),
            "customer_id": str(data.get("from_id", "") or ""),
            "customer_name": client.to_chinese(data.get("from_name", "") or data.get("cy_name", "")),
            "msg_id": str(data.get("msg_id", "") or ""),
            "msg_type": int(data.get("msg_type", 0) or 0),
            "msg": client.to_chinese(data.get("msg", "") or ""),
            "goods_name": client.to_chinese(data.get("goods_name", "") or ""),
            "goods_order": client.to_chinese(data.get("goods_order", "") or ""),
        }
        if extra:
            payload.update(extra)
        async with httpx.AsyncClient(timeout=6, trust_env=trust_env) as http_client:
            resp = await http_client.post(client._tianwang_callback_url, json=payload)
            ok = 200 <= resp.status_code < 300
            client._activity_log(
                "tianwang_callback",
                result="ok" if ok else "http_error",
                event_name=event,
                status_code=resp.status_code,
                acc_id=payload["acc_id"],
                customer_id=payload["customer_id"],
            )
    except Exception as e:
        client._activity_log(
            "tianwang_callback",
            result="error",
            event_name=event,
            acc_id=str(data.get("acc_id", "") or ""),
            customer_id=str(data.get("from_id", "") or ""),
            error=str(e),
        )
