#!/usr/bin/env python3
"""Réattribue tous les avatars du pack défis aux acheteurs"""

import mysql.connector
from python.db_config import DB_CONFIG

conn = mysql.connector.connect(**DB_CONFIG)
cursor = conn.cursor(dictionary=True)

print("=" * 60)
print("RÉATTRIBUTION DE TOUS LES AVATARS DU PACK DÉFIS")
print("=" * 60)

# 1. Récupérer tous les weekly_rewards
cursor.execute('SELECT week_key, avatar_id FROM weekly_rewards ORDER BY week_key')
weekly_rewards = cursor.fetchall()
print(f"\nWeekly rewards ({len(weekly_rewards)}):")
for r in weekly_rewards:
    print(f"  - {r['week_key']}: Avatar {r['avatar_id']}")

# 2. Récupérer tous les acheteurs du pack
cursor.execute('''
    SELECT ucp.user_id, u.display_name 
    FROM user_challenge_pack ucp
    JOIN users u ON u.id = ucp.user_id
''')
buyers = cursor.fetchall()
print(f"\nAcheteurs ({len(buyers)}):")
for b in buyers:
    print(f"  - {b['display_name']} (ID: {b['user_id']})")

# 3. Pour chaque acheteur, attribuer tous les avatars
print("\n" + "=" * 60)
print("ATTRIBUTION")
print("=" * 60)

for buyer in buyers:
    user_id = buyer['user_id']
    user_name = buyer['display_name']
    granted = 0
    
    print(f"\n--- {user_name} (ID: {user_id}) ---")
    
    for reward in weekly_rewards:
        week_key = reward['week_key']
        avatar_id = reward['avatar_id']
        
        # Vérifier que l'avatar existe
        cursor.execute('SELECT id FROM avatars WHERE id = %s', (avatar_id,))
        if not cursor.fetchone():
            print(f"  ⚠️ Avatar {avatar_id} n'existe pas, ignoré")
            continue
        
        # user_weekly_avatars
        cursor.execute('''
            SELECT 1 FROM user_weekly_avatars 
            WHERE user_id = %s AND avatar_id = %s
        ''', (user_id, avatar_id))
        
        if not cursor.fetchone():
            cursor.execute('''
                INSERT INTO user_weekly_avatars (user_id, avatar_id, week_key, obtained_at, obtained_from)
                VALUES (%s, %s, %s, NOW(), 'challenge_pack')
            ''', (user_id, avatar_id, week_key))
            print(f"  ✓ user_weekly_avatars: {week_key} -> Avatar {avatar_id}")
        
        # user_avatars
        cursor.execute('''
            SELECT 1 FROM user_avatars 
            WHERE user_id = %s AND avatar_id = %s
        ''', (user_id, avatar_id))
        
        if not cursor.fetchone():
            cursor.execute('''
                INSERT INTO user_avatars (user_id, avatar_id, source, metadata, unlocked_at)
                VALUES (%s, %s, 'challenge_pack', %s, NOW())
            ''', (user_id, avatar_id, f'{{"week_key": "{week_key}"}}'))
            print(f"  ✓ user_avatars: Avatar {avatar_id}")
            granted += 1
        else:
            print(f"  · Avatar {avatar_id} déjà présent")
    
    print(f"  -> {granted} nouveaux avatars attribués")

conn.commit()

# 4. Vérification finale
print("\n" + "=" * 60)
print("VÉRIFICATION FINALE - AVATARS DE BRUNO-ADMIN")
print("=" * 60)

cursor.execute('''
    SELECT ua.avatar_id, ua.source, ua.metadata, a.code, ua.unlocked_at
    FROM user_avatars ua
    JOIN avatars a ON a.id = ua.avatar_id
    WHERE ua.user_id = 1
    ORDER BY ua.avatar_id
''')
avatars = cursor.fetchall()
print(f"\nTotal: {len(avatars)} avatars dans user_avatars")
for a in avatars:
    print(f"  - {a['code']} (ID: {a['avatar_id']}) - source: {a['source']}, week: {a['metadata']}")

cursor.execute('''
    SELECT avatar_id, week_key, obtained_from
    FROM user_weekly_avatars 
    WHERE user_id = 1
    ORDER BY week_key
''')
weekly = cursor.fetchall()
print(f"\nTotal: {len(weekly)} avatars dans user_weekly_avatars")
for w in weekly:
    print(f"  - Semaine {w['week_key']}: Avatar {w['avatar_id']} ({w['obtained_from']})")

conn.close()
print("\n✅ Terminé!")
