"""
输出格式化 - 让推荐结果更友好
增加emoji、结构化展示、备选方案
"""
from typing import Dict, List, Optional
import random

class OutputFormatter:
    """输出格式化器"""

    # 礼物类型emoji映射
    GIFT_EMOJIS = {
        # 电子产品
        "机器人": "🤖",
        "耳机": "🎧",
        "手表": "⌚",
        "手环": "⌚",
        "相机": "📷",
        "键盘": "⌨️",
        "音箱": "🔊",
        
        # 美妆护理
        "护肤": "🧴",
        "口红": "💄",
        "香水": "🌸",
        "面膜": "🧖",
        
        # 服饰配饰
        "丝巾": "🎀",
        "项链": "💎",
        "戒指": "💍",
        "包包": "👜",
        "皮带": "👔",
        "钱包": "👛",
        "衣服": "👗",
        "鞋": "👟",
        "西装": "🤵",
        
        # 家居生活
        "按摩": "💆",
        "足浴": "🦶",
        "茶": "🍵",
        "咖啡": "☕",
        "酒": "🍷",
        "杯": "🥤",
        "绿植": "🌿",
        "花": "💐",
        "香薰": "🕯️",
        
        # 健康保健
        "保健": "💊",
        "血压": "🩺",
        "燕窝": "🥣",
        
        # 食品
        "月饼": "🥮",
        "巧克力": "🍫",
        "水果": "🍎",
        "零食": "🍪",
        
        # 玩具娱乐
        "乐高": "🧩",
        "玩具": "🎁",
        "游戏": "🎮",
        "书": "📚",
        
        # 其他
        "红包": "🧧",
        "券": "🎫",
        "旅行": "✈️",
        "摆件": "🏺",
    }

    # 推荐等级emoji
    SCORE_EMOJIS = {
        95: "🌟",  # 95分以上
        90: "⭐",  # 90分以上
        80: "✨",  # 80分以上
        0: "💡",   # 默认
    }

    def format_recommendation(self, result: Dict) -> str:
        """
        格式化推荐结果

        Args:
            result: API返回的结果

        Returns:
            格式化后的文本
        """
        # 如果需要追问
        if result.get("needs_clarification"):
            return self._format_clarification(result)

        # 如果没有推荐结果
        if not result.get("recommendations"):
            return self._format_no_result(result)

        # 正常推荐
        return self._format_success(result)

    def _format_clarification(self, result: Dict) -> str:
        """格式化追问"""
        questions = result.get("clarification_questions", [])
        if not questions:
            questions = ["请告诉我更多关于送礼的信息～"]

        lines = [
            "🤔 我需要了解更多信息才能帮你推荐：",
            ""
        ]
        for i, q in enumerate(questions, 1):
            lines.append(f"  {i}. {q}")
        
        lines.extend([
            "",
            "💡 小提示：比如「送女朋友生日礼物，预算500」"
        ])
        
        return "\n".join(lines)

    def _format_no_result(self, result: Dict) -> str:
        """格式化无结果"""
        query = result.get("query", {})
        return "\n".join([
            "😅 抱歉，没找到合适的推荐...",
            "",
            f"📋 查询条件：",
            f"   • 收礼人：{query.get('relation') or '未指定'}",
            f"   • 场合：{query.get('occasion') or '未指定'}",
            f"   • 预算：{query.get('budget')}",
            "",
            "💡 建议：试试调整预算或换个说法？"
        ])

    def _format_success(self, result: Dict) -> str:
        """格式化成功推荐"""
        query = result.get("query", {})
        recommendations = result.get("recommendations", [])
        blessing = result.get("blessing", "")

        lines = [
            "🎁 **礼物推荐来啦！**",
            ""
        ]

        # 主推荐（前3个）
        main_gifts = recommendations[:3]
        for i, gift in enumerate(main_gifts, 1):
            lines.extend(self._format_gift_item(i, gift, is_main=True))

        # 备选方案（如果有更多）
        if len(recommendations) > 3:
            backup_gifts = recommendations[3:5]
            lines.extend([
                "",
                "🔄 **备选方案：**"
            ])
            for gift in backup_gifts:
                lines.append(f"   • {self._get_gift_emoji(gift['name'])} {gift['name']} ~{gift['price']}元")

        # 祝福语
        if blessing:
            lines.extend([
                "",
                f"🎊 {blessing}"
            ])

        # 查询摘要
        lines.extend([
            "",
            "─── 查询摘要 ───",
            f"🎯 收礼人：{query.get('relation') or '未指定'}",
            f"🎉 场合：{query.get('occasion') or '未指定'}",
            f"💰 预算：{query.get('budget')}",
        ])

        # 提示换一个
        lines.extend([
            "",
            "💡 不满意？试试说「换一个」或调整预算～"
        ])

        return "\n".join(lines)

    def _format_gift_item(self, index: int, gift: Dict, is_main: bool = True) -> List[str]:
        """格式化单个礼物"""
        emoji = self._get_gift_emoji(gift["name"])
        score_emoji = self._get_score_emoji(gift.get("score", 80))
        
        lines = []
        
        # 标题行
        lines.append(
            f"**{index}. {emoji} {gift['name']}**  "
            f"~{gift['price']}元  {score_emoji}{gift.get('score', 85)}分"
        )
        
        # 推荐理由
        reason = gift.get("reason", "用心之选")
        lines.append(f"   💭 {reason}")
        
        lines.append("")
        
        return lines

    def _get_gift_emoji(self, name: str) -> str:
        """根据礼物名称获取emoji"""
        for keyword, emoji in self.GIFT_EMOJIS.items():
            if keyword in name:
                return emoji
        return "🎁"

    def _get_score_emoji(self, score: int) -> str:
        """根据分数获取emoji"""
        for threshold, emoji in sorted(self.SCORE_EMOJIS.items(), reverse=True):
            if score >= threshold:
                return emoji
        return "💡"


def format_recommendation(result: Dict) -> str:
    """便捷函数"""
    formatter = OutputFormatter()
    return formatter.format_recommendation(result)
