#!/usr/bin/env python
"""
Batch test: tạo catalog nhỏ từ DB và chạy _compute_matches cho 1 sản phẩm.
"""
import sys, os, json, sqlite3

# MUST set before importing engine
os.environ['USE_LOCAL_SQLITE'] = 'True'

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

from worker.stylist_engine import StylistEngine

print("=== BATCH TEST (Simplified) ===\n")

engine = StylistEngine()
print(f"[+] Engine loaded. Rules: {len(engine.rules['occasions'])} occasions, weights: {engine.rules['score_weights']}")

catalog = engine._get_catalog()
print(f"[+] Catalog size: {len(catalog)} products")

if len(catalog) == 0:
    print("[!] Catalog empty - check DB connections (StarRocks/Postgres)")
    sys.exit(1)

# Get valid anchor categories from SQLite DB (seeded rules)
import sqlite3
conn_sqlite = sqlite3.connect('database/canifa_ai_dump.sqlite')
cur_sqlite = conn_sqlite.cursor()
cur_sqlite.execute("SELECT DISTINCT anchor_category FROM chatbot_fashion_rules")
valid_anchors = {row[0].lower() for row in cur_sqlite.fetchall()}
cur_sqlite.close()
conn_sqlite.close()

print(f"[+] Valid anchor categories from DB: {len(valid_anchors)} categories")

test_product = None
for p in catalog:
    pl = p.get("product_line", "").lower()
    if pl in valid_anchors:
        test_product = p
        break

if not test_product:
    print("[!] No catalog product matches any anchored product line in DB rules")
    print("[!] Available anchors:", valid_anchors)
    sys.exit(1)

print(f"[+] Testing with product code: {test_product['code']}")
print(f"    Product line: {test_product['product_line']}")
print(f"    Color: {test_product['color']}")
print(f"    Gender: {test_product['gender']}")

print("\n[+] Running _compute_matches...")
matches = engine._compute_matches(test_product, catalog[:50])

print(f"\n[+] Result: {len(matches)} occasions generated")
for occ, roles in matches.items():
    print(f"\n  Occasion: {occ}")
    for role, items in roles.items():
        print(f"    {role}: {len(items)} items")
        for item in items[:2]:
            print(f"      - {item['code']} ({item['product_line']}) score={item['score']}")

print("\n[+] Batch test completed successfully!")
