"""
Script pour créer les 19 avatars du pack "cool" dans la table avatars
Ces avatars sont nécessaires avant de créer les liens dans pack_avatars

Usage:
    python python/migrations/create_cool_avatars.py
"""
import sys
from pathlib import Path

sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
from db_config import DB_CONFIG


def create_cool_avatars():
    """Crée les 19 avatars du pack cool dans la table avatars"""
    try:
        import mysql.connector
        from mysql.connector import Error
    except ModuleNotFoundError:
        print("❌ Module mysql-connector-python requis")
        print("Installation: pip install mysql-connector-python")
        return False

    connection = None
    try:
        print("🔗 Connexion à la base de données OVH...")
        connection = mysql.connector.connect(**DB_CONFIG)
        cursor = connection.cursor(dictionary=True)

        # Vérifier combien d'avatars cool existent déjà
        cursor.execute("""
            SELECT id, code 
            FROM avatars 
            WHERE code LIKE 'cool_%'
            ORDER BY code
        """)
        existing_cool = cursor.fetchall()

        if existing_cool:
            print(f"✅ {len(existing_cool)} avatar(s) 'cool' déjà présent(s):")
            for avatar in existing_cool:
                print(f"   - {avatar['code']} (ID: {avatar['id']})")
            
            response = input("\nVoulez-vous continuer et ajouter les manquants ? (o/N): ")
            if response.lower() != 'o':
                print("❌ Opération annulée")
                return False

        # Générer les 19 avatars cool
        print(f"\n📝 Création des avatars du pack 'cool'...")
        created = 0
        skipped = 0
        
        for i in range(1, 20):  # cool_01 à cool_19
            code = f"cool_{i:02d}"
            file_path = f"avatars/cool/cool_{i:02d}.png"
            
            # Vérifier si l'avatar existe déjà
            cursor.execute("SELECT id FROM avatars WHERE code = %s", (code,))
            if cursor.fetchone():
                print(f"   ⏭️  {code} existe déjà")
                skipped += 1
                continue
            
            try:
                cursor.execute("""
                    INSERT INTO avatars (code, category, file_path, price, display_order)
                    VALUES (%s, 'achat', %s, 0, %s)
                """, (code, file_path, 500 + i))
                created += 1
                print(f"   ✅ {code} créé")
            except Error as e:
                print(f"   ❌ Erreur pour {code}: {e}")

        connection.commit()
        
        print(f"\n{'='*60}")
        print(f"✅ Création terminée:")
        print(f"   - Créés: {created}")
        print(f"   - Existants: {skipped}")
        print(f"   - Total: {created + skipped}/19")
        print(f"{'='*60}")

        # Afficher tous les avatars cool
        cursor.execute("""
            SELECT id, code, file_path 
            FROM avatars 
            WHERE code LIKE 'cool_%'
            ORDER BY code
        """)
        all_cool = cursor.fetchall()
        
        print(f"\n📋 Liste complète des avatars 'cool' ({len(all_cool)}):")
        for avatar in all_cool:
            print(f"   ID {avatar['id']:3d}: {avatar['code']} → {avatar['file_path']}")

        if len(all_cool) != 19:
            print(f"\n⚠️  ATTENTION: {len(all_cool)} avatars trouvés, 19 attendus")
        else:
            print(f"\n✅ Les 19 avatars du pack 'cool' sont prêts")
            print("   Vous pouvez maintenant exécuter: python/migrations/create_pack_avatars_table.py")

        return True

    except Error as e:
        print(f"\n❌ Erreur MySQL: {e}")
        if connection and connection.is_connected():
            connection.rollback()
        return False

    finally:
        if connection and connection.is_connected():
            cursor.close()
            connection.close()
            print("\n🔌 Connexion fermée")


if __name__ == "__main__":
    print("="*60)
    print("CRÉATION: Avatars du pack 'cool'")
    print("="*60)
    print()
    
    success = create_cool_avatars()
    
    if not success:
        print("\n❌ Création échouée")
        sys.exit(1)
    else:
        print("\n✅ Création terminée avec succès")
        sys.exit(0)
