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

sys.path.insert(0, os.path.dirname(__file__))
sys.stdout.reconfigure(encoding='utf-8') if hasattr(sys.stdout, 'reconfigure') else None

print("=== LOADING 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)
product_line_to_role = rules['product_line_to_role']
score_weights = rules['score_weights']

print(f"Weights: {score_weights}")

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

def get_role(pl):
    return product_line_to_role.get(pl, None)

print("\n=== COLOR SCORE TESTS (expected from JSON matrices) ===")
tests = [
    ("Trắng", "Đen", 30),   # neutral-neutral
    ("Trắng", "Hồng", 22),  # neutral-light: matrix neutral.light = 22? Actually color_group_matrix.neutral.light = 22
    ("Đen", "Trắng", 30),
    ("Be", "Nâu", 30),      # both neutral -> 30
    ("Xanh lam", "Trắng", 22), # light-neutral: matrix light.neutral = 22
    ("Đỏ", "Trắng", 20),    # dark-neutral: matrix dark.neutral = 20
    ("Hồng", "Đen", 22),    # light-neutral
    ("Cam", "Trắng", 20),   # dark-neutral
]
passed = 0
for src, tgt, expected in tests:
    score = color_score(src, tgt)
    ok = score == expected
    passed += ok
    print(f"  {src:12} -> {tgt:12}: {score:3} (exp {expected:3}) {'OK' if ok else 'FAIL'}")
print(f"Color tests: {passed}/{len(tests)} passed")

print("\n=== ROLE MAPPING TESTS ===")
test_pl = [
    ("Áo Sơ mi", "top"),
    ("Quần âu", "bottom"),
    ("Blazer", "outerwear"),
    ("Chân váy", "bottom"),
    ("Mũ", "accessory"),
    ("Cardigan", "outerwear"),
    ("Áo phông", "top"),
]
passed = 0
for pl, expected in test_pl:
    role = get_role(pl)
    ok = role == expected
    if role is None:
        print(f"  {pl:15} -> {'None':10} (exp {expected:10}) FAIL (not in mapping)")
    else:
        passed += ok
        print(f"  {pl:15} -> {role:10} (exp {expected:10}) {'OK' if ok else 'FAIL'}")
print(f"Role tests: {passed}/{len(test_pl)} passed")

print("\n=== SEED DATA CHECK ===")
import sqlite3
db_path = 'database/canifa_ai_dump.sqlite'
conn = sqlite3.connect(db_path)
cur = conn.cursor()
cur.execute("SELECT COUNT(*) FROM chatbot_fashion_rules")
count = cur.fetchone()[0]
cur.execute("SELECT DISTINCT occasion_tag FROM chatbot_fashion_rules")
occasions = [row[0] for row in cur.fetchall()]
cur.execute("SELECT anchor_category, target_category, match_role FROM chatbot_fashion_rules LIMIT 3")
samples = cur.fetchall()
conn.close()

print(f"Total rules: {count}")
print(f"Occasions: {occasions}")
print(f"Sample rules:")
for s in samples:
    print(f"  {s[0]} + {s[1]} -> {s[2]}")
print("\n[+] All checks complete. Ready for batch test.")
