#!/usr/bin/env python3
"""nlp.py — 自然语言指令解析器"""
import re
from typing import Dict, Any

# More specific patterns first, generic ones later
_QQ = [
    (r"(查|看|搜索|找).*offer.?id.*?([A-Za-z0-9_-]+)", "query_product", "offer_id", 2),
    (r"(查|看|搜索|找).*(商品|产品|SKU|sku|id).*?(\d+)", "query_product", "product_id", 3),
    (r"(查|看|搜索|找).*id.*?(\d+)", "query_product", "product_id", 2),
    (r"(库存|缺货|断货|无货)", "check_stock", None, None),
    (r"(统计|概览|汇总|总览|状态|有多少|总数|总计)", "show_stats", None, None),
    (r"(健康分|评分|score).*?(\d+)", "check_health", "min_score", 2),
    (r"(低分|低健康|异常|预警)", "check_health", None, None),
    (r"(启动|执行|运行).*?任务#?(\d+)", "run_task", "task_id", 2),
    (r"(停止|暂停|取消).*?任务#?(\d+)", "stop_task", "task_id", 2),
    (r"任务.*?(列表|查看|显示)", "list_tasks", None, None),
    (r"(同步|刷新|更新).*(Ozon|ozon|商品|数据)", "sync_ozon", None, None),
    (r"(发送|推送).*(告警|通知)", "send_alert", None, None),
]

def parse(text: str) -> Dict[str, Any]:
    r = {"intent":"unknown","entities":{},"raw":text.strip(),"confidence":0.0,"response":""}
    for pat, intent, ek, gi in _QQ:
        m = re.search(pat, r["raw"])
        if m:
            r["intent"] = intent
            r["confidence"] = round(0.7, 2)
            if ek and gi and m.lastindex and m.lastindex >= gi:
                val = m.group(gi)
                if val.isdigit(): val = int(val)
                r["entities"][ek] = val
            return r
    return r
