"""
Validation script: Tìm tất cả SP đang phối sai tuổi / giới tính.
Output: Danh sách các cặp (source, target) bị lỗi.
"""
from worker.stylist_engine import StylistEngine

e = StylistEngine()
catalog = e._get_catalog()
catalog_map = {p['code']: p for p in catalog}

KID_KEYWORDS = ['boy', 'girl', 'bé', 'trẻ em']

def is_kid(product):
    g  = (product.get('gender') or '').lower()
    ag = (product.get('age_group') or '').lower()
    return any(k in g+ag for k in KID_KEYWORDS)

def is_unisex(g):
    return 'unisex' in g.lower()

errors = []
ok_count = 0
total_pairs = 0

print("Computing matches for all products (this may take ~30s)...")
# Sample: run for first 50 products to validate fast; remove [:50] for full
sample = catalog  # full catalog

for src in sample:
    matches = e.compute_dynamic_rule_matches(src['code'])
    src_kid = is_kid(src)
    sg = (src.get('gender') or '').lower()

    for occ, roles in matches.items():
        for role, items in roles.items():
            for it in items:
                tgt = catalog_map.get(it['code'])
                if not tgt:
                    continue
                total_pairs += 1
                tgt_kid = is_kid(tgt)
                tg = (tgt.get('gender') or '').lower()

                # Rule 1: Kids vs Adults
                if src_kid != tgt_kid:
                    errors.append({
                        'type': 'AGE_MISMATCH',
                        'src': f"{src['code']} ({src.get('name','')[:30]}) gender={sg}",
                        'tgt': f"{it['code']} ({it.get('name','')[:30]}) gender={tg}",
                        'occ': occ, 'role': role
                    })
                    continue

                # Rule 2: Gender mismatch (excluding unisex)
                if sg and tg and not is_unisex(sg) and not is_unisex(tg) and sg != tg:
                    errors.append({
                        'type': 'GENDER_MISMATCH',
                        'src': f"{src['code']} ({src.get('name','')[:30]}) gender={sg}",
                        'tgt': f"{it['code']} ({it.get('name','')[:30]}) gender={tg}",
                        'occ': occ, 'role': role
                    })
                    continue

                ok_count += 1

print(f"\n{'='*70}")
print(f"Total pairs checked : {total_pairs}")
print(f"OK pairs            : {ok_count}")
print(f"ERRORS found        : {len(errors)}")
print(f"{'='*70}")

if errors:
    print("\n=== ERRORS (first 30) ===")
    for i, err in enumerate(errors[:30]):
        print(f"[{err['type']}] {err['src']}")
        print(f"          → {err['tgt']}  ({err['occ']}/{err['role']})")
        print()
else:
    print("\n✅ ALL PAIRS CLEAN! Gender & Age match 100%")
