"""
Script de migration pour créer la table pack_avatars et configurer le pack "cool"
Cette table est nécessaire pour le webhook Stripe des packs d'avatars.

Usage:
    python python/migrations/create_pack_avatars_table.py
"""
import sys
from pathlib import Path

# Ajouter le parent au path pour importer db_config
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
from db_config import DB_CONFIG


def create_pack_avatars_table():
    """Crée la table pack_avatars et configure le pack cool"""
    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 si la table existe déjà
        cursor.execute("""
            SELECT COUNT(*) as count 
            FROM information_schema.tables 
            WHERE table_schema = %s 
            AND table_name = 'pack_avatars'
        """, (DB_CONFIG['database'],))
        
        result = cursor.fetchone()
        table_exists = result['count'] > 0

        if table_exists:
            print("✅ La table 'pack_avatars' existe déjà")
            cursor.execute("SELECT COUNT(*) as count FROM pack_avatars")
            count_result = cursor.fetchone()
            print(f"   📊 {count_result['count']} entrées actuelles")
        else:
            print("📝 Création de la table 'pack_avatars'...")
            cursor.execute("""
                CREATE TABLE `pack_avatars` (
                  `pack_id` varchar(50) NOT NULL,
                  `avatar_id` int NOT NULL,
                  `display_order` int DEFAULT 0,
                  PRIMARY KEY (`pack_id`, `avatar_id`),
                  KEY `idx_pack_avatars_pack` (`pack_id`),
                  KEY `idx_pack_avatars_avatar` (`avatar_id`),
                  CONSTRAINT `pack_avatars_ibfk_1` FOREIGN KEY (`pack_id`) 
                    REFERENCES `avatar_packs` (`pack_id`) ON DELETE CASCADE,
                  CONSTRAINT `pack_avatars_ibfk_2` FOREIGN KEY (`avatar_id`) 
                    REFERENCES `avatars` (`id`) ON DELETE CASCADE
                ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci
            """)
            connection.commit()
            print("✅ Table 'pack_avatars' créée avec succès")

        # Vérifier si le pack "cool" existe
        print("\n🔍 Vérification du pack 'cool'...")
        cursor.execute("""
            SELECT pack_id, name, avatar_count 
            FROM avatar_packs 
            WHERE pack_id = 'cool'
        """)
        cool_pack = cursor.fetchone()

        if not cool_pack:
            print("⚠️  Le pack 'cool' n'existe pas dans avatar_packs")
            print("   Création recommandée via: sql/migrations/add_avatar_packs.sql")
            return False

        print(f"✅ Pack trouvé: {cool_pack['name']} ({cool_pack['avatar_count']} avatars)")

        # Chercher les avatars du pack cool
        print("\n🔍 Recherche des avatars pour le pack 'cool'...")
        
        # Chercher les avatars avec code commençant par 'cool'
        cursor.execute("""
            SELECT id, code, category, file_path 
            FROM avatars 
            WHERE code LIKE 'cool%' OR code LIKE 'cool_%'
            ORDER BY code
        """)
        cool_avatars = cursor.fetchall()

        if not cool_avatars:
            print("⚠️  Aucun avatar avec code 'cool*' trouvé dans la base")
            print("   Les avatars du pack 'cool' doivent être ajoutés à la table avatars")
            print("\n💡 Suggestion: Créer les avatars cool manuellement:")
            print("   - Catégorie: 'achat'")
            print("   - Codes: 'cool_01' à 'cool_19'")
            print("   - Chemins: 'avatars/cool/cool_XX.png'")
            return False

        print(f"✅ {len(cool_avatars)} avatars trouvés:")
        for avatar in cool_avatars:
            print(f"   - ID {avatar['id']}: {avatar['code']} ({avatar['category']})")

        # Vérifier combien sont déjà dans pack_avatars
        cursor.execute("""
            SELECT COUNT(*) as count 
            FROM pack_avatars 
            WHERE pack_id = 'cool'
        """)
        existing_count = cursor.fetchone()['count']

        if existing_count > 0:
            print(f"\n⚠️  {existing_count} avatar(s) déjà lié(s) au pack 'cool'")
            response = input("   Voulez-vous réinitialiser et recréer les liens ? (o/N): ")
            if response.lower() == 'o':
                cursor.execute("DELETE FROM pack_avatars WHERE pack_id = 'cool'")
                connection.commit()
                print("   ✅ Liens existants supprimés")
            else:
                print("   ℹ️  Conservation des liens existants")
                return True

        # Insérer les avatars dans pack_avatars
        print(f"\n📝 Insertion de {len(cool_avatars)} avatars dans 'pack_avatars'...")
        inserted = 0
        
        for i, avatar in enumerate(cool_avatars):
            try:
                cursor.execute("""
                    INSERT INTO pack_avatars (pack_id, avatar_id, display_order)
                    VALUES ('cool', %s, %s)
                    ON DUPLICATE KEY UPDATE display_order = VALUES(display_order)
                """, (avatar['id'], i + 1))
                inserted += 1
            except Error as e:
                print(f"   ⚠️  Erreur pour avatar ID {avatar['id']}: {e}")

        connection.commit()
        print(f"✅ {inserted} avatar(s) lié(s) au pack 'cool'")

        # Vérification finale
        print("\n🔍 Vérification finale...")
        cursor.execute("""
            SELECT pa.pack_id, pa.avatar_id, pa.display_order, a.code, a.file_path
            FROM pack_avatars pa
            JOIN avatars a ON pa.avatar_id = a.id
            WHERE pa.pack_id = 'cool'
            ORDER BY pa.display_order
        """)
        final_avatars = cursor.fetchall()

        print(f"✅ Pack 'cool' configuré avec {len(final_avatars)} avatar(s):")
        for avatar in final_avatars[:5]:  # Afficher les 5 premiers
            print(f"   {avatar['display_order']:2d}. {avatar['code']}")
        if len(final_avatars) > 5:
            print(f"   ... et {len(final_avatars) - 5} autres")

        # Vérifier que le compte correspond
        if len(final_avatars) != cool_pack['avatar_count']:
            print(f"\n⚠️  ATTENTION: {len(final_avatars)} avatars configurés, mais {cool_pack['avatar_count']} annoncés dans avatar_packs")
            print("   Mise à jour du compteur...")
            cursor.execute("""
                UPDATE avatar_packs 
                SET avatar_count = %s 
                WHERE pack_id = 'cool'
            """, (len(final_avatars),))
            connection.commit()
            print("   ✅ Compteur mis à jour")

        print("\n" + "="*60)
        print("✅ MIGRATION RÉUSSIE")
        print("="*60)
        print(f"Table: pack_avatars")
        print(f"Pack: cool ({len(final_avatars)} avatars)")
        print(f"Status: Prêt pour le webhook Stripe")
        print("="*60)

        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("MIGRATION: Table pack_avatars")
    print("="*60)
    print()
    
    success = create_pack_avatars_table()
    
    if not success:
        print("\n❌ Migration échouée ou incomplète")
        print("\nActions recommandées:")
        print("1. Vérifier que le pack 'cool' existe dans avatar_packs")
        print("2. Créer les avatars 'cool_01' à 'cool_19' dans la table avatars")
        print("3. Relancer ce script")
        sys.exit(1)
    else:
        print("\n✅ Migration terminée avec succès")
        sys.exit(0)
