"""
商城购物推荐工具 - 为业主提供智能购物推荐服务
"""
import json
from typing import Optional, List
from langchain.tools import tool
import logging
from datetime import datetime

logger = logging.getLogger(__name__)

# Mock商城商品数据（实际部署时从真实商城API获取）
MALL_PRODUCTS = {
    "家居清洁": [
        {
            "id": "P001",
            "name": "蓝月亮洗衣液 3kg家庭装",
            "price": 49.9,
            "original_price": 69.9,
            "discount": "限时7折",
            "description": "温和配方，深层洁净，呵护衣物",
            "category": "家居清洁",
            "tags": ["热销", "家庭必备"],
            "stock": 156,
            "sales": 2341,
            "rating": 4.8,
            "image": "https://example.com/images/laundry.jpg",
            "link": "https://mall.jiuchen.com/product/P001"
        },
        {
            "id": "P002",
            "name": "威猛先生厨房油污净 500ml*2",
            "price": 35.8,
            "original_price": 45.8,
            "discount": "买2送1",
            "description": "强力去油污，一喷即净",
            "category": "家居清洁",
            "tags": ["促销", "厨房必备"],
            "stock": 89,
            "sales": 1567,
            "rating": 4.7,
            "image": "https://example.com/images/kitchen_cleaner.jpg",
            "link": "https://mall.jiuchen.com/product/P002"
        },
        {
            "id": "P003",
            "name": "扫地机器人 智能规划款",
            "price": 1299,
            "original_price": 1699,
            "discount": "新品特惠",
            "description": "智能规划路线，APP远程控制，解放双手",
            "category": "家居清洁",
            "tags": ["智能家电", "热销"],
            "stock": 23,
            "sales": 456,
            "rating": 4.9,
            "image": "https://example.com/images/robot_vacuum.jpg",
            "link": "https://mall.jiuchen.com/product/P003"
        }
    ],
    "生鲜果蔬": [
        {
            "id": "F001",
            "name": "云南高原蓝莓 125g*4盒",
            "price": 39.9,
            "original_price": 59.9,
            "discount": "产地直发",
            "description": "新鲜采摘，果粒饱满，酸甜可口",
            "category": "生鲜果蔬",
            "tags": ["新鲜", "热销"],
            "stock": 67,
            "sales": 1892,
            "rating": 4.9,
            "image": "https://example.com/images/blueberry.jpg",
            "link": "https://mall.jiuchen.com/product/F001"
        },
        {
            "id": "F002",
            "name": "进口车厘子 2斤装",
            "price": 89.9,
            "original_price": 129.9,
            "discount": "限时特价",
            "description": "智利进口，个大饱满，甜度高",
            "category": "生鲜果蔬",
            "tags": ["进口", "高品质"],
            "stock": 34,
            "sales": 876,
            "rating": 4.8,
            "image": "https://example.com/images/cherry.jpg",
            "link": "https://mall.jiuchen.com/product/F002"
        },
        {
            "id": "F003",
            "name": "有机蔬菜礼盒 3kg装",
            "price": 68,
            "original_price": 88,
            "discount": "会员专享",
            "description": "当季有机蔬菜，新鲜配送，健康放心",
            "category": "生鲜果蔬",
            "tags": ["有机", "健康"],
            "stock": 45,
            "sales": 1234,
            "rating": 4.7,
            "image": "https://example.com/images/vegetables.jpg",
            "link": "https://mall.jiuchen.com/product/F003"
        }
    ],
    "家电数码": [
        {
            "id": "E001",
            "name": "小米智能门锁 Pro",
            "price": 1599,
            "original_price": 1999,
            "discount": "新品上市",
            "description": "指纹密码钥匙三合一，远程APP查看",
            "category": "家电数码",
            "tags": ["智能", "安全"],
            "stock": 12,
            "sales": 345,
            "rating": 4.9,
            "image": "https://example.com/images/smart_lock.jpg",
            "link": "https://mall.jiuchen.com/product/E001"
        },
        {
            "id": "E002",
            "name": "戴森吸尘器 V12",
            "price": 3999,
            "original_price": 4499,
            "discount": "限时优惠",
            "description": "强劲吸力，轻便无线，全屋清洁",
            "category": "家电数码",
            "tags": ["高端", "热销"],
            "stock": 8,
            "sales": 234,
            "rating": 4.8,
            "image": "https://example.com/images/dyson.jpg",
            "link": "https://mall.jiuchen.com/product/E002"
        }
    ],
    "日用百货": [
        {
            "id": "D001",
            "name": "维达抽纸 3层100抽*24包",
            "price": 59.9,
            "original_price": 79.9,
            "discount": "囤货必备",
            "description": "3层加厚，柔韧亲肤，不易破损",
            "category": "日用百货",
            "tags": ["家庭必备", "囤货"],
            "stock": 234,
            "sales": 5678,
            "rating": 4.8,
            "image": "https://example.com/images/tissue.jpg",
            "link": "https://mall.jiuchen.com/product/D001"
        },
        {
            "id": "D002",
            "name": "垃圾桶 智能感应款",
            "price": 159,
            "original_price": 199,
            "discount": "新品特惠",
            "description": "红外感应开盖，静音设计，防臭密封",
            "category": "日用百货",
            "tags": ["智能", "居家好物"],
            "stock": 67,
            "sales": 890,
            "rating": 4.7,
            "image": "https://example.com/images/trash_can.jpg",
            "link": "https://mall.jiuchen.com/product/D002"
        }
    ],
    "母婴用品": [
        {
            "id": "M001",
            "name": "帮宝适纸尿裤 M码 102片",
            "price": 169,
            "original_price": 199,
            "discount": "满2件9折",
            "description": "柔软透气，12小时干爽，呵护宝宝肌肤",
            "category": "母婴用品",
            "tags": ["热销", "宝妈推荐"],
            "stock": 89,
            "sales": 3456,
            "rating": 4.9,
            "image": "https://example.com/images/diaper.jpg",
            "link": "https://mall.jiuchen.com/product/M001"
        },
        {
            "id": "M002",
            "name": "婴幼儿辅食机",
            "price": 299,
            "original_price": 399,
            "discount": "限时特价",
            "description": "多功能一体机，蒸煮搅拌，做辅食更轻松",
            "category": "母婴用品",
            "tags": ["辅食", "实用"],
            "stock": 34,
            "sales": 567,
            "rating": 4.8,
            "image": "https://example.com/images/baby_food_maker.jpg",
            "link": "https://mall.jiuchen.com/product/M002"
        }
    ],
    "宠物用品": [
        {
            "id": "PET001",
            "name": "皇家猫粮 2kg装",
            "price": 89,
            "original_price": 109,
            "discount": "会员价",
            "description": "均衡营养，呵护猫咪健康，挑嘴猫也爱吃",
            "category": "宠物用品",
            "tags": ["进口", "营养"],
            "stock": 56,
            "sales": 1234,
            "rating": 4.8,
            "image": "https://example.com/images/cat_food.jpg",
            "link": "https://mall.jiuchen.com/product/PET001"
        },
        {
            "id": "PET002",
            "name": "智能宠物喂食器",
            "price": 299,
            "original_price": 399,
            "discount": "新品优惠",
            "description": "定时定量投喂，APP远程控制，出差旅行必备",
            "category": "宠物用品",
            "tags": ["智能", "便捷"],
            "stock": 23,
            "sales": 456,
            "rating": 4.7,
            "image": "https://example.com/images/pet_feeder.jpg",
            "link": "https://mall.jiuchen.com/product/PET002"
        }
    ]
}


@tool
def get_mall_categories() -> str:
    """
    获取商城商品分类列表。
    
    返回：
        商品分类JSON字符串
    """
    categories = []
    for category, products in MALL_PRODUCTS.items():
        categories.append({
            "name": category,
            "product_count": len(products),
            "hot_tags": list(set([tag for p in products for tag in p.get("tags", [])]))[:3]
        })
    
    return json.dumps({
        "success": True,
        "count": len(categories),
        "categories": categories,
        "message": "玖辰商城现有6大品类，涵盖家居清洁、生鲜果蔬、家电数码、日用百货、母婴用品、宠物用品，欢迎选购~"
    }, ensure_ascii=False)


@tool
def search_products(
    keyword: Optional[str] = None,
    category: Optional[str] = None,
    max_price: Optional[float] = None,
    min_price: Optional[float] = None,
    tags: Optional[str] = None,
    limit: int = 5
) -> str:
    """
    搜索商城商品。
    
    参数：
        keyword: 搜索关键词（商品名称、描述等）
        category: 商品分类（家居清洁/生鲜果蔬/家电数码/日用百货/母婴用品/宠物用品）
        max_price: 最高价格
        min_price: 最低价格
        tags: 商品标签（热销/新品/促销等）
        limit: 返回数量限制，默认5条
    
    返回：
        商品列表JSON字符串
    """
    results = []
    
    # 确定要搜索的分类
    search_categories = [category] if category else list(MALL_PRODUCTS.keys())
    
    for cat in search_categories:
        if cat not in MALL_PRODUCTS:
            continue
            
        for product in MALL_PRODUCTS[cat]:
            # 关键词匹配
            if keyword:
                keyword_lower = keyword.lower()
                if (keyword_lower not in product["name"].lower() and 
                    keyword_lower not in product["description"].lower()):
                    continue
            
            # 价格过滤
            if max_price and product["price"] > max_price:
                continue
            if min_price and product["price"] < min_price:
                continue
            
            # 标签过滤
            if tags:
                if tags not in product.get("tags", []):
                    continue
            
            # 添加分类信息
            product_copy = product.copy()
            product_copy["category"] = cat
            results.append(product_copy)
    
    # 按销量排序
    results.sort(key=lambda x: x["sales"], reverse=True)
    
    # 限制返回数量
    results = results[:limit]
    
    if results:
        return json.dumps({
            "success": True,
            "count": len(results),
            "products": results,
            "message": f"为您找到{len(results)}件相关商品~"
        }, ensure_ascii=False)
    else:
        return json.dumps({
            "success": True,
            "count": 0,
            "products": [],
            "message": "暂未找到相关商品，换个关键词试试？"
        }, ensure_ascii=False)


@tool
def recommend_products(
    scene: Optional[str] = None,
    user_need: Optional[str] = None,
    budget: Optional[str] = None,
    limit: int = 3
) -> str:
    """
    为用户智能推荐商品。
    
    适用场景：
    - 业主询问"有什么好用的..."
    - 业主有具体需求（如"家里有宠物"、"家里有宝宝"）
    - 业主想买礼物
    - 业主想囤货
    - 季节性推荐（如"夏天到了"、"冬天来了"）
    
    参数：
        scene: 使用场景（如：家庭清洁、母婴、宠物、送礼、囤货、换季等）
        user_need: 用户具体需求描述
        budget: 预算范围（如：100元以内、200-500元、不限）
        limit: 推荐数量，默认3条
    
    返回：
        推荐商品列表JSON字符串
    """
    recommendations = []
    
    # 场景到分类和标签的映射
    scene_mapping = {
        "家庭清洁": {"categories": ["家居清洁", "日用百货"], "tags": ["家庭必备", "清洁"]},
        "清洁": {"categories": ["家居清洁"], "tags": ["热销"]},
        "母婴": {"categories": ["母婴用品"], "tags": ["宝妈推荐", "热销"]},
        "宝宝": {"categories": ["母婴用品"], "tags": ["热销"]},
        "宠物": {"categories": ["宠物用品"], "tags": ["营养", "智能"]},
        "猫": {"categories": ["宠物用品"], "tags": ["进口"]},
        "狗": {"categories": ["宠物用品"], "tags": ["营养"]},
        "送礼": {"categories": ["生鲜果蔬", "家电数码"], "tags": ["高端", "进口"]},
        "囤货": {"categories": ["日用百货", "家居清洁"], "tags": ["囤货", "家庭必备"]},
        "换季": {"categories": ["家居清洁"], "tags": ["促销"]},
        "夏天": {"categories": ["生鲜果蔬", "家电数码"], "tags": ["新鲜", "智能"]},
        "冬天": {"categories": ["家居清洁", "日用百货"], "tags": ["热销"]},
        "智能": {"categories": ["家电数码", "日用百货"], "tags": ["智能"]},
        "家电": {"categories": ["家电数码"], "tags": ["热销", "智能"]},
        "水果": {"categories": ["生鲜果蔬"], "tags": ["新鲜", "进口"]},
        "蔬菜": {"categories": ["生鲜果蔬"], "tags": ["有机", "健康"]},
    }
    
    # 解析预算
    budget_max = None
    if budget:
        if "以内" in budget or "以下" in budget:
            try:
                budget_max = float(''.join(filter(str.isdigit, budget)))
            except:
                pass
    
    # 确定搜索范围
    search_cats = []
    search_tags = []
    
    if scene and scene in scene_mapping:
        search_cats = scene_mapping[scene]["categories"]
        search_tags = scene_mapping[scene]["tags"]
    
    # 如果有用户需求描述，尝试匹配
    if user_need:
        for keyword, mapping in scene_mapping.items():
            if keyword in user_need:
                search_cats.extend(mapping["categories"])
                search_tags.extend(mapping["tags"])
    
    # 如果没有匹配到场景，搜索所有分类
    if not search_cats:
        search_cats = list(MALL_PRODUCTS.keys())
    
    # 去重
    search_cats = list(set(search_cats))
    
    # 收集推荐商品
    for cat in search_cats:
        if cat not in MALL_PRODUCTS:
            continue
            
        for product in MALL_PRODUCTS[cat]:
            # 预算过滤
            if budget_max and product["price"] > budget_max:
                continue
            
            # 计算推荐分数
            score = 0
            for tag in product.get("tags", []):
                if tag in search_tags:
                    score += 10
            
            score += product["rating"] * 5
            score += min(product["sales"] / 100, 20)
            
            product_copy = product.copy()
            product_copy["category"] = cat
            product_copy["recommend_score"] = score
            recommendations.append(product_copy)
    
    # 按推荐分数排序
    recommendations.sort(key=lambda x: x["recommend_score"], reverse=True)
    
    # 限制数量
    recommendations = recommendations[:limit]
    
    if recommendations:
        # 生成推荐理由
        for i, product in enumerate(recommendations):
            reasons = []
            if product.get("discount"):
                reasons.append(f"正在{product['discount']}")
            if product.get("rating", 0) >= 4.8:
                reasons.append(f"好评率{product['rating']}分")
            if product.get("sales", 0) > 1000:
                reasons.append(f"已售{product['sales']}件")
            product["recommend_reason"] = "，".join(reasons) if reasons else "精选好物"
        
        return json.dumps({
            "success": True,
            "count": len(recommendations),
            "scene": scene,
            "recommendations": recommendations,
            "message": f"根据您的需求，为您精选{len(recommendations)}件好物~"
        }, ensure_ascii=False)
    else:
        return json.dumps({
            "success": True,
            "count": 0,
            "recommendations": [],
            "message": "暂无合适的推荐，换个需求试试？"
        }, ensure_ascii=False)


@tool
def get_hot_deals(limit: int = 5) -> str:
    """
    获取商城热门优惠商品。
    
    返回：
        热门优惠商品列表JSON字符串
    """
    all_products = []
    
    for category, products in MALL_PRODUCTS.items():
        for product in products:
            product_copy = product.copy()
            product_copy["category"] = category
            
            # 计算优惠力度
            if product.get("original_price") and product.get("price"):
                discount_rate = (product["original_price"] - product["price"]) / product["original_price"]
                product_copy["discount_rate"] = round(discount_rate * 100, 1)
            else:
                product_copy["discount_rate"] = 0
            
            all_products.append(product_copy)
    
    # 按优惠力度+销量排序
    all_products.sort(key=lambda x: x["discount_rate"] * 50 + min(x["sales"] / 100, 30), reverse=True)
    
    hot_deals = all_products[:limit]
    
    return json.dumps({
        "success": True,
        "count": len(hot_deals),
        "hot_deals": hot_deals,
        "message": "🔥 今日热门优惠，限时抢购中~"
    }, ensure_ascii=False)


@tool
def get_product_detail(product_id: str) -> str:
    """
    获取商品详细信息。
    
    参数：
        product_id: 商品ID
    
    返回：
        商品详情JSON字符串
    """
    for category, products in MALL_PRODUCTS.items():
        for product in products:
            if product["id"] == product_id:
                product_copy = product.copy()
                product_copy["category"] = category
                return json.dumps({
                    "success": True,
                    "product": product_copy,
                    "message": f"商品详情：{product['name']}"
                }, ensure_ascii=False)
    
    return json.dumps({
        "success": False,
        "error": f"未找到商品ID: {product_id}"
    }, ensure_ascii=False)
