import sys
import json
import logging

try:
    from worker.stylist_engine import StylistEngine
except ImportError:
    print("❌ LỖI: Không import được StylistEngine.")
    sys.exit(1)

logging.basicConfig(level=logging.ERROR)

def dict_to_string(d):
    return json.dumps(d, ensure_ascii=False, indent=2)

def main():
    engine = StylistEngine()
    catalog = engine._get_catalog()
    
    adult_nam = None
    adult_nu = None

    for p in catalog:
        gender = str(p.get("gender") or "").lower()
        age = str(p.get("age_group") or "").lower()
        name = str(p.get("name") or "").lower()

        if not adult_nam and (gender == 'nam' or gender == 'men') and 'bé' not in name and 'kid' not in age:
            adult_nam = p
            
        elif not adult_nu and (gender == 'nữ' or gender == 'nu' or gender == 'women') and 'bé' not in name and 'kid' not in age:
            adult_nu = p
            
        if adult_nam and adult_nu:
            break

    print("================ PRODUCT MATCHES EXPORT =================\n")
    for label, subj in [("Người lớn (Nam)", adult_nam), ("Người lớn (Nữ)", adult_nu)]:
        if not subj: continue
        code = subj['code']
        print(f"--- TEST CASE: {label} ---")
        print(f"Sản phẩm gốc: Tên={subj['name']} | Mã={code} | Giới tính={subj.get('gender')}")
        
        matches = engine.compute_dynamic_rule_matches(code)
        
        print("\n[BẢNG PHỐI ĐỒ (Dịp mặc)]:")
        if matches:
            for occ, roles in matches.items():
                print(f"  Dịp: {occ}")
                for role, items in roles.items():
                    print(f"    - Role: {role}")
                    for item in items[:3]:
                        item_name = str(item.get('name') or "")
                        item_gender = str(item.get('gender') or "")
                        print(f"        -> {item['code']} | {item_name} (Gender: {item_gender})")
        
        print("\n[PHÂN NHÓM MỞ RỘNG RAW SQL]:")
        classifications = engine.compute_super_classifications_sql(code)
        if classifications:
            for group, g_dict in classifications.items():
                for key, items in g_dict.items():
                    print(f"  Nhóm: {group} -> {key}")
                    for item in items[:2]:
                        item_name = str(item.get('name') or "")
                        item_gender = str(item.get('gender_by_product') or "")
                        print(f"        -> {item['magento_ref_code']} | {item_name} (Gender: {item_gender})")
        print("\n\n")

if __name__ == "__main__":
    main()
