from __future__ import annotations

import asyncio
import logging
from typing import TYPE_CHECKING, Optional
from core.post_ops import record_deal_success
from core.order_helpers import parse_order_info

logger = logging.getLogger("cs_agent")

if TYPE_CHECKING:
    from core.pydantic_ai_agent import AgentResponse, ConversationState, CustomerMessage, CustomerServiceAgent


async def handle_order_notification(
    agent: "CustomerServiceAgent",
    *,
    message: "CustomerMessage",
    state: "ConversationState",
) -> Optional["AgentResponse"]:
    """Handle system order notifications before normal AI dialogue."""
    from core.pydantic_ai_agent import AgentResponse

    if "系统订单信息" not in message.msg and "订单状态" not in message.msg:
        return None

    _, order_block = agent._split_customer_text(message.msg)
    customer_text, _ = agent._split_customer_text(message.msg)
    order = parse_order_info(order_block or message.msg)
    pay_status = order.get("pay_status", "")
    order_status = order.get("order_status", "")

    paid_keywords = ["等待发货", "已付款", "付款成功", "买家已付款"]
    is_paid = any(kw in pay_status or kw in order_status for kw in paid_keywords)

    if is_paid:
        asyncio.create_task(agent._check_order_amount(message.from_id, order, message.acc_id))
        asyncio.create_task(
            record_deal_success(
                customer_id=message.from_id,
                customer_name=message.from_name,
                acc_id=message.acc_id,
                platform=message.acc_type,
                order=order,
                state=state,
            )
        )
        try:
            from core.workflow import workflow

            asyncio.create_task(
                workflow.trigger_processing_on_payment(
                    customer_id=message.from_id,
                    acc_id=message.acc_id,
                    acc_type=message.acc_type,
                )
            )
        except Exception as e:
            logger.exception("[Agent] 触发作图失败: %s", e)
    elif not customer_text:
        logger.info("[Agent] 订单通知静默（%s），跳过回复", pay_status or order_status)
        return AgentResponse(reply="", should_reply=False, need_transfer=False)

    return None
