"""
输入解析 - 解析自然语言输入
优化版：支持更好的关系映射和信息不足检测
"""
from typing import Dict, Optional, List
import re

class InputParser:
    """自然语言输入解析器"""

    # 关系关键词及映射（优先级从高到低）
    RELATION_MAPPINGS = [
        # 完整匹配
        ("女朋友", "女友"),
        ("女友", "女友"),
        ("男朋友", "男友"),
        ("男友", "男友"),
        ("老婆", "老婆"),
        ("老公", "老公"),
       ("妈妈", "妈妈"),
        ("爸爸", "爸爸"),
        ("母亲", "妈妈"),
        ("父亲", "爸爸"),
        ("闺蜜", "闺蜜"),
        ("兄弟", "兄弟"),
        ("老师", "老师"),
        ("领导", "领导"),
        ("同事", "同事"),
        ("客户", "客户"),
        ("长辈", "长辈"),
        ("孩子", "孩子"),
        ("学生", "学生"),
        ("朋友", "朋友"),  # 放在最后，避免误匹配
        ("", "未知"),  # 无关系
    ]

    # 场合关键词及映射
    OCCASION_MAPPINGS = [
        ("生日", "生日"),
        ("情人节", "情人节"),
        ("纪念日", "纪念日"),
        ("结婚纪念日", "结婚纪念日"),
        ("母亲节", "母亲节"),
        ("父亲节", "父亲节"),
        ("教师节", "教师节"),
        ("春节", "春节"),
        ("中秋", "中秋节"),
        ("中秋节", "中秋节"),
        ("乔迁", "乔迁"),
        ("结婚", "结婚"),
        ("婚礼", "结婚"),
        ("看望", "看望"),
        ("道歉", "道歉"),
        ("感谢", "感谢"),
        ("表白", "表白"),
        ("商务", "商务"),
        ("升职", "升职"),
        ("退休", "退休"),
    ]

    # 预算模式
    BUDGET_PATTERNS = [
        # 范围预算: "500-1000" "500到1000"
        (r"(\d+)\s*[-到~]\s*(\d+)", "range"),
        # 单点预算: "500元左右" "预算500"
        (r"(?:预算\s*)?(\d+)[元块]?(?:左右|以内|以下)?", "single"),
    ]

    def parse(self, text: str) -> Dict:
        """
        解析输入文本

        Args:
            text: 用户输入

        Returns:
            解析结果 {relation, occasion, budget_min, budget_max, needs_clarification, missing_fields}
        """
        result = {
            "relation": None,
            "occasion": None,
            "budget_min": None,
            "budget_max": None,
            "needs_clarification": False,
            "missing_fields": [],
            "original_text": text,
        }

        # 提取关系（按优先级匹配）
        for keyword, mapped in self.RELATION_MAPPINGS:
            if keyword in text:
                result["relation"] = mapped
                break

        # 提取场合
        for keyword, mapped in self.OCCASION_MAPPINGS:
            if keyword in text:
                result["occasion"] = mapped
                break

        # 提取预算
        for pattern, mode in self.BUDGET_PATTERNS:
            match = re.search(pattern, text)
            if match:
                groups = match.groups()
                if mode == "range" and len(groups) == 2:
                    result["budget_min"] = int(groups[0])
                    result["budget_max"] = int(groups[1])
                else:
                    budget = int(groups[0])
                    result["budget_min"] = int(budget * 0.8)
                    result["budget_max"] = int(budget * 1.2)
                break

        # 检测是否需要追问
        result["missing_fields"] = self._check_missing_fields(result)
        result["needs_clarification"] = len(result["missing_fields"]) > 0

        return result

    def _check_missing_fields(self, result: Dict) -> List[str]:
        """检查缺失的必要字段"""
        missing = []
        
        # 关系是必须的
        if not result["relation"]:
            missing.append("relation")
        
        # 场合是必须的（除非是日常送礼）
        if not result["occasion"]:
            missing.append("occasion")
        
        # 预算可选（有默认建议）
        # if not result["budget_max"]:
        #     missing.append("budget")

        return missing

    def get_clarification_questions(self, missing_fields: List[str]) -> List[str]:
        """根据缺失字段生成追问问题"""
        questions = []
        
        if "relation" in missing_fields:
            questions.append("🎁 送给谁呢？（比如：妈妈、女友、朋友、领导...）")
        
        if "occasion" in missing_fields:
            questions.append("🎉 什么场合？（比如：生日、情人节、乔迁...）")
        
        return questions
