from __future__ import annotations

import json
from typing import Any

from agentscope.tool import ToolResponse

from .rules import (
    detect_intent,
    detect_order_status,
    extract_image_urls,
    extract_size_pairs_m,
    has_map_or_political_risk,
    has_porn_risk,
    is_meaningless_short,
    requests_external_contact,
)


def _tool_ok(value: Any) -> ToolResponse:
    """Wrap python values into AgentScope ToolResponse."""
    try:
        text = json.dumps(value, ensure_ascii=False)
    except Exception:
        text = str(value)
    return ToolResponse(
        content=[{"type": "text", "text": text}],
        metadata={"value": value},
    )


def tool_detect_intent(msg: str) -> ToolResponse:
    """识别客户当前意图: image/pricing/greeting/external_contact/finish_or_quote_trigger/nonsense/unknown。"""
    return _tool_ok(detect_intent(msg or ""))


def tool_extract_image_urls(msg: str) -> ToolResponse:
    """提取消息中的图片 URL 列表。"""
    return _tool_ok(extract_image_urls(msg or ""))


def tool_detect_order_status(goods_order: str) -> ToolResponse:
    """识别订单状态: paid/pending_payment/refund/unknown。"""
    return _tool_ok(detect_order_status(goods_order or ""))


def tool_extract_size_pairs(msg: str) -> ToolResponse:
    """提取尺寸对，单位米。返回 [(w, h), ...]。"""
    return _tool_ok(extract_size_pairs_m(msg or ""))


def tool_detect_risk(msg: str, goods_name: str = "") -> ToolResponse:
    """检测风险：地图政治、黄暴。"""
    text = msg or ""
    gname = goods_name or ""
    return _tool_ok(
        {
            "map_or_political": has_map_or_political_risk(text, gname),
            "porn": has_porn_risk(text),
        }
    )


def tool_detect_external_contact(msg: str) -> ToolResponse:
    """检测是否索要外部联系方式（微信/QQ/手机号等）。"""
    return _tool_ok(requests_external_contact(msg or ""))


def tool_is_meaningless_short(msg: str) -> ToolResponse:
    """检测是否无意义短句（嗯/哦/ok等）。"""
    return _tool_ok(is_meaningless_short(msg or ""))
