"""
Script pour vérifier si tous les scripts SQL locaux ont été appliqués sur OVH CloudDB
"""
from python.db_config import DB_CONFIG

def verify_migrations():
    try:
        try:
            import mysql.connector  # type: ignore
            from mysql.connector import Error  # type: ignore
        except ModuleNotFoundError:
            print("❌ Dépendance manquante: mysql-connector-python")
            print()
            print("Installe-la puis relance:")
            print("  pip install mysql-connector-python")
            print("  python3 python/migrations/verify_sql_migrations.py")
            return

        connection = mysql.connector.connect(**DB_CONFIG)

        if connection.is_connected():
            cursor = connection.cursor()
            
            print("=" * 80)
            print("VÉRIFICATION DES MIGRATIONS SQL")
            print("=" * 80)
            print()
            
            # 1. Vérifier app_config
            print("📋 1. app_config - Vérification des configurations")
            print("-" * 60)
            cursor.execute("SELECT config_key, config_value FROM app_config")
            configs = cursor.fetchall()
            print(f"   Configurations trouvées: {len(configs)}")
            for key, value in configs:
                print(f"   - {key}: {value[:50]}{'...' if len(value) > 50 else ''}")
            
            # Vérifier les configs attendues
            expected_configs = ['ambient_music', 'public_theme', 'maintenance_mode', 'maintenance_message', 'challenge_pack_enabled']
            found_configs = [c[0] for c in configs]
            for ec in expected_configs:
                status = "✅" if ec in found_configs else "❌"
                print(f"   {status} {ec}")
            print()
            
            # 2. Vérifier avatars de base
            print("📋 2. sql/seeds/insert_base_avatars.sql - Avatars de base")
            print("-" * 60)
            cursor.execute("SELECT COUNT(*) FROM avatars WHERE category = 'base'")
            base_avatars = cursor.fetchone()[0]
            status = "✅" if base_avatars == 20 else "❌"
            print(f"   {status} Avatars de base: {base_avatars}/20")
            print()
            
            # 3. Vérifier wallet_history + audit_log.installation_id
            print("📋 3. sql/migrations/add_wallet_history.sql - wallet_history + audit_log.installation_id")
            print("-" * 60)
            cursor.execute("SHOW TABLES LIKE 'wallet_history'")
            wallet_history_exists = cursor.fetchone() is not None
            status = "✅" if wallet_history_exists else "❌"
            result = "Existe" if wallet_history_exists else "N'existe PAS"
            print(f"   {status} Table wallet_history: {result}")

            cursor.execute(
                "SHOW COLUMNS FROM audit_log LIKE 'installation_id'"
            )
            installation_id_exists = cursor.fetchone() is not None
            status = "✅" if installation_id_exists else "❌"
            result = "Existe" if installation_id_exists else "N'existe PAS"
            print(f"   {status} Colonne audit_log.installation_id: {result}")
            print()
            
            # 4. Vérifier weekly challenges tables
            print("📋 4. sql/migrations/add_weekly_challenges.sql - Tables défis hebdomadaires")
            print("-" * 60)
            tables_weekly = ['weekly_rewards', 'used_weekly_avatars', 'weekly_progress', 'user_weekly_avatars']
            for table in tables_weekly:
                cursor.execute(f"SHOW TABLES LIKE '{table}'")
                exists = cursor.fetchone() is not None
                status = "✅" if exists else "❌"
                if exists:
                    cursor.execute(f"SELECT COUNT(*) FROM {table}")
                    count = cursor.fetchone()[0]
                    print(f"   {status} {table}: {count} enregistrements")
                else:
                    print(f"   {status} {table}: N'existe PAS")
            print()
            
            # 5. Vérifier music_volume dans user_settings
            print("📋 5. sql/migrations/add_music_volume.sql - Colonne music_volume")
            print("-" * 60)
            cursor.execute("SHOW COLUMNS FROM user_settings LIKE 'music_volume'")
            music_vol_exists = cursor.fetchone() is not None
            status = "✅" if music_vol_exists else "❌"
            result = "Existe" if music_vol_exists else "N'existe PAS"
            print(f"   {status} Colonne music_volume: {result}")
            print()
            
            # 6. Vérifier challenge pack
            print("📋 6. sql/migrations/add_challenge_pack.sql - Pack Défis")
            print("-" * 60)
            cursor.execute("SHOW TABLES LIKE 'user_challenge_pack'")
            challenge_pack_exists = cursor.fetchone() is not None
            status = "✅" if challenge_pack_exists else "❌"
            result = "Existe" if challenge_pack_exists else "N'existe PAS"
            print(f"   {status} Table user_challenge_pack: {result}")
            
            cursor.execute("SHOW TABLES LIKE 'daily_challenges'")
            daily_challenges_exists = cursor.fetchone() is not None
            status = "✅" if daily_challenges_exists else "❌"
            if daily_challenges_exists:
                cursor.execute("SELECT COUNT(*) FROM daily_challenges")
                count = cursor.fetchone()[0]
                print(f"   {status} Table daily_challenges: {count} enregistrements")
            else:
                print(f"   {status} Table daily_challenges: N'existe PAS")
            print()
            
            # 7. Vérifier bonus tables
            print("📋 7. sql/migrations/add_bonus_tables.sql - Tables bonus quotidien/arcade")
            print("-" * 60)
            for table in ['daily_bonus', 'arcade_bonus']:
                cursor.execute(f"SHOW TABLES LIKE '{table}'")
                exists = cursor.fetchone() is not None
                status = "✅" if exists else "❌"
                if exists:
                    cursor.execute(f"SELECT COUNT(*) FROM {table}")
                    count = cursor.fetchone()[0]
                    print(f"   {status} {table}: {count} enregistrements")
                else:
                    print(f"   {status} {table}: N'existe PAS")
            print()
            
            # 8. Vérifier avatar packs
            print("📋 8. sql/migrations/add_avatar_packs.sql (+ sql/migrations/add_pack_avatars.sql) - Packs d'avatars premium")
            print("-" * 60)
            for table in ['avatar_packs', 'pack_avatars', 'user_avatar_packs']:
                cursor.execute(f"SHOW TABLES LIKE '{table}'")
                exists = cursor.fetchone() is not None
                status = "✅" if exists else "❌"
                if exists:
                    cursor.execute(f"SELECT COUNT(*) FROM {table}")
                    count = cursor.fetchone()[0]
                    print(f"   {status} {table}: {count} enregistrements")
                else:
                    print(f"   {status} {table}: N'existe PAS")
            
            # Vérifier le pack Cool
            cursor.execute("SELECT pack_id, name, price FROM avatar_packs WHERE pack_id = 'cool'")
            cool_pack = cursor.fetchone()
            if cool_pack:
                print(f"   ✅ Pack 'cool' trouvé: {cool_pack[1]} à {cool_pack[2]}€")
            else:
                print(f"   ❌ Pack 'cool' non trouvé")
            print()

            # 9. Vérifier payment_transactions.pack_type
            print("📋 9. sql/migrations/add_payment_pack_type.sql - Colonne payment_transactions.pack_type")
            print("-" * 60)
            cursor.execute("SHOW COLUMNS FROM payment_transactions LIKE 'pack_type'")
            pack_type_exists = cursor.fetchone() is not None
            status = "✅" if pack_type_exists else "❌"
            result = "Existe" if pack_type_exists else "N'existe PAS"
            print(f"   {status} Colonne pack_type: {result}")
            print()
            
            print("=" * 80)
            print("RÉSUMÉ")
            print("=" * 80)

    except Error as e:
        print(f"❌ Erreur de connexion MySQL: {e}")
    
    finally:
        if connection.is_connected():
            cursor.close()
            connection.close()
            print("\n🔌 Connexion fermée")

if __name__ == "__main__":
    verify_migrations()
