import logging

from utils.observability import build_trace_id
from core.websocket_brain_flow import decide_brain_action, execute_brain_action

logger = logging.getLogger("cs_agent")


async def handle_agent_reply_flow(client, data: dict, *, workflow, shop_type_resolver):
    """处理单条消息：统一走 Brain 决策 + 执行。"""
    try:
        msg_text = client.to_chinese(data.get("msg", ""))
        customer_id = data.get("from_id", "")
        trace_id = build_trace_id(data.get("acc_id", ""), customer_id, data.get("msg_id", ""), msg_text[:64])
        data["_trace_id"] = trace_id
        shop_type = shop_type_resolver(data.get("acc_id", ""), client.to_chinese(data.get("goods_name", "") or ""))

        customer_msg = client._build_customer_message(data)
        decision = await decide_brain_action(
            client,
            data,
            customer_msg,
            trace_id=trace_id,
            msg_text=msg_text,
            shop_type=shop_type,
        )
        client._activity_log(
            "brain_decision",
            trace_id=trace_id,
            acc_id=data.get("acc_id", ""),
            customer_id=data.get("from_id", ""),
            action=decision.action,
            source=decision.source,
            should_reply=bool(decision.should_reply),
            need_transfer=bool(decision.need_transfer),
        )
        await execute_brain_action(
            client,
            data,
            decision=decision,
            trace_id=trace_id,
            msg_text=msg_text,
        )

    except Exception as e:
        logger.error("Agent 处理失败: %s", e)
        client._activity_log(
            "agent_process_error",
            trace_id=data.get("_trace_id", ""),
            acc_id=data.get("acc_id", ""),
            customer_id=data.get("from_id", ""),
            error=str(e),
        )
