"""Quick script to check product_line + gender + age distribution in ultra_descriptions."""
import sys, os
sys.path.append(os.path.dirname(os.path.abspath(__file__)))
from common.pool_wrapper import get_pooled_connection_compat

conn = get_pooled_connection_compat()
cur = conn.cursor()

# 1. Check distinct product_line values + gender + age
cur.execute("""
    SELECT 
        product_line, 
        description_data->>'gioi_tinh' as gender,
        description_data->>'do_tuoi' as age,
        COUNT(*) as cnt
    FROM dashboard_canifa.ultra_descriptions
    GROUP BY product_line, description_data->>'gioi_tinh', description_data->>'do_tuoi'
    ORDER BY product_line, gender, age
""")
rows = cur.fetchall()
print("=" * 80)
print(f"{'Product Line':<35} {'Gender':<15} {'Age':<15} {'Count':>6}")
print("=" * 80)
for r in rows:
    print(f"{str(r[0] or ''):<35} {str(r[1] or 'NULL'):<15} {str(r[2] or 'NULL'):<15} {r[3]:>6}")

print(f"\nTotal groups: {len(rows)}")

# 2. Check sample tags
cur.execute("""
    SELECT product_line, tags, COUNT(*) 
    FROM dashboard_canifa.ultra_descriptions 
    WHERE tags IS NOT NULL AND tags::text != '[]' AND tags::text != 'null'
    GROUP BY product_line, tags 
    ORDER BY COUNT(*) DESC 
    LIMIT 20
""")
print("\n\n" + "=" * 80)
print("SAMPLE TAGS (top 20 combos)")
print("=" * 80)
for r in cur.fetchall():
    print(f"{str(r[0] or ''):<35} {str(r[1])[:60]:<62} x{r[2]}")

# 3. Count products with/without tags
cur.execute("""
    SELECT 
        COUNT(*) FILTER (WHERE tags IS NOT NULL AND tags::text != '[]' AND tags::text != 'null') as has_tags,
        COUNT(*) FILTER (WHERE tags IS NULL OR tags::text = '[]' OR tags::text = 'null') as no_tags,
        COUNT(*) as total
    FROM dashboard_canifa.ultra_descriptions
""")
r = cur.fetchone()
print(f"\n📊 Has tags: {r[0]} | No tags: {r[1]} | Total: {r[2]}")

cur.close()
conn.close()
