import json
import psycopg

def check_data():
    print("Initiating DB connection...")
    try:
        conn = psycopg.connect("host=160.191.50.138 port=5432 dbname=law_bot user=law_user password=zvPQhfGgYwhY0ihKOTRNjN4wH")
        cur = conn.cursor()

        query = """
            SELECT magento_ref_code, name, gender, ai_matches 
            FROM dashboard_canifa.ultra_descriptions
            WHERE ai_matches IS NOT NULL AND ai_matches != '{}'::jsonb
              AND (gender = 'Nam' OR gender = 'Nữ' OR gender = 'nam' OR gender = 'nu') 
            LIMIT 10;
        """
        
        cur.execute(query)
        rows = cur.fetchall()
        
        print(f"Found {len(rows)} products with ai_matches")
        
        for row in rows:
            code = row[0]
            name = row[1]
            gender = row[2]
            matches = row[3]
            
            print(f"\n--- Code: {code} | Name: {name} | Gender: {gender} ---")
            if isinstance(matches, str):
                matches = json.loads(matches)
                
            if not matches:
                print("  No match data!")
                continue
                
            has_issue = False
            for occasion, roles in matches.items():
                print(f"  Occasion: {occasion}")
                for role, items in roles.items():
                    for item in items[:3]:
                        item_gender = item.get('gender', 'unknown').lower()
                        item_name = item.get('name', 'unknown')
                        item_cat = item.get('category', 'unknown').lower()
                        
                        is_kid = ('bé' in item_gender or 'be_' in item_gender or 'girl' in item_gender or 
                                  'boy' in item_gender or 'be gai' in item_gender or 'be trai' in item_gender)
                        is_kid_name = ('bé' in item_name.lower())
                        
                        if is_kid or is_kid_name:
                            has_issue = True
                            print(f"      -> {item.get('code')}: {item_name}")
                            print(f"         *** ISSUE: KID'S ITEM (Gender: {item_gender}) IN ADULT MATCH ({gender}) ***")

            if not has_issue:
                print("  OK (No demographic mismatch found in top items).")

        cur.close()
        conn.close()
    except Exception as e:
        print(f"Error: {e}")

if __name__ == "__main__":
    check_data()
