"""
筛选逻辑：
1. 品类筛选：基于主推款，筛选可搭配品类，允许的品类组合：上装+裤装，上装+半裙，外套+连衣裙，外套+裤装，外套+连衣裙，上装+裤装+外套，上装+裙装+外套    
2. 颜色筛选：色彩，可同色调搭配，可对比色调搭配，整体色彩不超过三种，（排除红绿搭配）
3. 季节筛选：季节：同季节可互搭 春秋款可互搭 春夏款可互搭 秋冬款可互搭 夏季和冬季不可搭配
"""

from utils.logger_config import setup_logger
from utils.tools import read_json_file, has_four_color

logger = setup_logger(__name__)

class FilterGoods:
    def __init__(self, filter_config_file):

        self.filter_config = read_json_file(filter_config_file)

        # 定义商品类别层级关系
        self.category_hierarchy = self.filter_config["category_hierarchy"]

        # 定义商品颜色层级关系
        self.color_hierarchy = self.filter_config["color_hierarchy"]

        # 品类组合
        self.allowed_category_combos = {
            frozenset({'上装', '裤装'}),
            frozenset({'上装', '半裙'}),
            frozenset({'外套', '连衣裙'}),
            frozenset({'外套', '裤装'}),
            frozenset({"上装", "裤装", "外套"}),
            frozenset({"上装", "半裙", "外套"})
        }

        # 季节搭配
        self.allowed_season_combos = {
            frozenset({'春季', '春季'}),
            frozenset({'秋季', '秋季'}),
            frozenset({'夏季', '夏季'}),
            frozenset({'冬季', '冬季'}),
            frozenset({'初夏', '初夏'}),
            frozenset({'初冬', '初冬'}),
            frozenset({'夏季', '初夏'}),
            frozenset({'冬季', '初冬'}),
            frozenset({'春季', '秋季'}),
            frozenset({'春季', '夏季'}),
            frozenset({'春季', '初夏'}),
            frozenset({'秋季', '初冬'}),
            frozenset({'秋季', '冬季'})
        }

        # 色彩搭配
        self.not_allowed_color_combos = {
            frozenset({'红色', '绿色'})
        }

    def can_combine(self, goods_list):
        if len(goods_list) < 2:
            return False

        return (
            self._check_category_combo(goods_list) and
            self._check_season_combo(goods_list) and
            self._check_color_combo(goods_list)
        )

    def _get_top_category(self, category):
        """
        获取商品的最顶层类别
        :param category: 商品的具体类别
        :return: 顶层类别
        """
        for top_cat, sub_cats in self.category_hierarchy.items():
            if category == top_cat or category in sub_cats:
                return top_cat
        return category 
    
    def _check_category_combo(self, goods_list):
        """检查品类组合是否允许"""
        # 获取所有商品的顶层类别
        top_categories = set()
        for good in goods_list:
            category = good["category"]
            top_category = self._get_top_category(category)
            top_categories.add(top_category)
        
        # 检查顶层类别组合是否在允许的组合中
        if_can_combine = frozenset(top_categories) in self.allowed_category_combos
        logger.info(f"can_category_combine: {if_can_combine}")
        return if_can_combine

    def _check_season_combo(self, goods_list):
        season = frozenset(goods['season'] for goods in goods_list)
        if_can_combine = season in self.allowed_season_combos
        logger.info(f"can_season_combine: {if_can_combine}")
        return if_can_combine

    def _get_top_color(self, color):
        """
        获取商品的最顶层颜色
        :param category: 商品的具体颜色
        :return: 顶层颜色
        """
        for top_col, sub_col in self.color_hierarchy.items():
            if color == top_col or color in sub_col:
                return top_col
        return color

    def _check_color_combo(self, goods_list):
        """检查品类组合是否允许"""
        # 获取所有商品的顶层颜色
        top_colors = set()
        for good in goods_list:
            color = good["color"]
            top_color = self._get_top_color(color)
            top_colors.add(top_color)
        
        color_text = ''.join(top_colors)
        if_four_color = has_four_color(color_text)

        # 检查顶层类别组合是否在允许的组合中
        if_can_combine = frozenset(top_colors) not in self.not_allowed_color_combos and not(if_four_color)
        logger.info(f"can_color_combine: {if_can_combine}")
        return if_can_combine

filter_goods = FilterGoods('./config/filter_config.json')

if __name__ == "__main__":

    filter_goods = FilterGoods('./config/filter_config.json')

    goods1 = {"category": "T恤", "color": "红色", "season": "秋季"}  # 属于"上装"
    goods2 = {"category": "牛仔裤", "color": "军绿", "season": "春季"}  # 属于"裤装"
    goods3 = {"category": "外套", "color": "灰紫色", "season": "秋季"}  # 属于"外套"

    print(filter_goods.can_combine([goods1, goods2]))  # T恤+牛仔裤 -> 上装+下装，应返回True
    print(filter_goods.can_combine([goods1, goods2, goods3]))  # 上装+下装+外套，应返回True