#!/usr/bin/env python3
"""
Script para eliminar marcas específicas y limpiar marcas sin vehículos
"""

import sqlite3
import os

def remove_brands_and_cleanup():
    # Verificar que la base de datos exista
    db_path = "vehicle_database/vehicle_database.db"
    if not os.path.exists(db_path):
        print(f"Error: Base de datos no encontrada en {db_path}")
        return

    conn = sqlite3.connect(db_path)
    cursor = conn.cursor()

    print("Verificando marcas en la base de datos...")

    # Mostrar todas las marcas
    cursor.execute("SELECT id, name FROM brands ORDER BY name")
    all_brands = cursor.fetchall()
    print("Todas las marcas en la base de datos:")
    for brand_id, brand_name in all_brands:
        print(f"  ID: {brand_id}, Nombre: '{brand_name}'")

    # Marcas a eliminar (ahora con las mayúsculas exactas según lo que vimos en el resultado anterior)
    brands_to_remove = ['Ford', 'Toyota', 'Nissan', 'Honda', 'Chevrolet']
    
    print(f"\nMarcas a eliminar: {', '.join(brands_to_remove)}")
    
    try:
        # Contar cuántos vehículos tenemos para estas marcas antes de eliminar
        placeholders = ','.join(['?' for _ in brands_to_remove])
        cursor.execute(f"""
            SELECT COUNT(*) 
            FROM model_year_engine mye
            JOIN models m ON mye.model_id = m.id
            JOIN brands b ON m.brand_id = b.id
            WHERE b.name IN ({placeholders})
        """, brands_to_remove)
        count_to_delete = cursor.fetchone()[0]
        
        print(f"Se eliminarán {count_to_delete} vehículos de las marcas especificadas")

        if count_to_delete > 0:
            print("Procediendo con la eliminación...")
            
            # Eliminar las combinaciones modelo-año-motor para los modelos de las marcas especificadas
            cursor.execute(f"""
                DELETE FROM model_year_engine 
                WHERE model_id IN (
                    SELECT m.id FROM models m
                    JOIN brands b ON m.brand_id = b.id
                    WHERE b.name IN ({placeholders})
                )
            """, brands_to_remove)
            
            # Eliminar los modelos de las marcas especificadas
            cursor.execute(f"""
                DELETE FROM models 
                WHERE brand_id IN (
                    SELECT id FROM brands WHERE name IN ({placeholders})
                )
            """, brands_to_remove)
        
        # Eliminar las marcas especificadas
        cursor.execute(f"""
            DELETE FROM brands 
            WHERE name IN ({placeholders})
        """, brands_to_remove)
        
        # Eliminar marcas que no tienen modelos asociados
        print("Eliminando marcas sin vehículos...")
        cursor.execute("""
            DELETE FROM brands 
            WHERE id NOT IN (
                SELECT DISTINCT brand_id FROM models
            )
        """)
        
        conn.commit()
        
        # Mostrar un resumen de la base de datos actualizada
        print("\nResumen de la base de datos actualizada:")
        
        # Contar vehículos restantes
        cursor.execute("""
            SELECT COUNT(*) 
            FROM model_year_engine mye
            JOIN models m ON mye.model_id = m.id
            JOIN brands b ON m.brand_id = b.id
        """)
        total_vehicles = cursor.fetchone()[0]
        print(f"Total de vehículos restantes: {total_vehicles}")
        
        # Contar marcas restantes
        cursor.execute("SELECT COUNT(*) FROM brands")
        total_brands = cursor.fetchone()[0]
        print(f"Total de marcas restantes: {total_brands}")
        
        # Mostrar marcas restantes
        cursor.execute("SELECT name FROM brands ORDER BY name")
        remaining_brands = cursor.fetchall()
        print(f"Marcas restantes: {[brand[0] for brand in remaining_brands]}")
        
        # Mostrar rango de años actual
        cursor.execute("""
            SELECT MIN(y.year), MAX(y.year) 
            FROM years y
            JOIN model_year_engine mye ON y.id = mye.year_id
        """)
        min_year, max_year = cursor.fetchone()
        if min_year and max_year:
            print(f"Rango de años actual: {min_year} - {max_year}")
        else:
            print("No hay años con vehículos registrados")

    except Exception as e:
        print(f"Error al eliminar marcas y limpiar la base de datos: {e}")
        conn.rollback()
    finally:
        conn.close()

if __name__ == "__main__":
    remove_brands_and_cleanup()