#!/usr/bin/env python
import sys, os, json

sys.path.insert(0, os.path.dirname(__file__))

# Load rules
with open('worker/fashion_rules.json', 'r', encoding='utf-8') as f:
    rules = json.load(f)

color_keys = rules['color_keys']
color_groups = rules['color_groups']
color_matrix = rules['color_matrix']
default_color_score = rules.get('default_color_score', 12)

def detect_color(color_str):
    c = color_str.lower()
    for key, variants in color_keys.items():
        if any(v in c for v in variants):
            return key
    return None

def color_score(src_color, tgt_color):
    src_key = detect_color(src_color)
    tgt_key = detect_color(tgt_color)
    if src_key and tgt_key:
        src_group = color_groups.get(src_key)
        tgt_group = color_groups.get(tgt_key)
        if src_group and tgt_group:
            group_matrix = rules.get('color_group_matrix', {})
            return group_matrix.get(src_group, {}).get(tgt_group, default_color_score)
        else:
            row = color_matrix.get(src_key, {})
            return row.get(tgt_key, default_color_score)
    return default_color_score

# Test cases
tests = [
    ("Trắng", "Đen", 30),  # neutral-neutral
    ("Trắng", "Hồng", 20),  # neutral-light (from matrix)
    ("Đen", "Trắng", 30),
    ("Be", "Nâu", 25),
    ("Xanh lam", "Trắng", 25),
    ("Đỏ", "Trắng", 28),
]

print("=== COLOR SCORE TESTS ===")
for src, tgt, expected in tests:
    score = color_score(src, tgt)
    status = "OK" if score == expected else f"FAIL (got {score})"
    print(f"  {src} -> {tgt}: {score} (expected {expected}) {status}")

# Role mapping
product_line_to_role = rules['product_line_to_role']
print("\n=== ROLE MAPPING TESTS ===")
test_pl = ["Áo Sơ mi", "Quần âu", "Blazer", "Chân váy", "Mũ"]
for pl in test_pl:
    role = product_line_to_role.get(pl, "UNKNOWN")
    print(f"  {pl}: {role}")

# Weights
print("\n=== SCORE WEIGHTS ===")
print(f"  {rules['score_weights']}")

print("\n[+] Test logic OK")
