#!/usr/bin/env python3
"""
Script para agregar datos adicionales de Acura a la base de datos de vehículos
"""

import sqlite3
import os

def add_acura_additional_data():
    # 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("Agregando datos adicionales de Acura a la base de datos...")

    try:
        # Asegurar que la marca Acura exista
        cursor.execute("INSERT OR IGNORE INTO brands (name) VALUES (?)", ("ACURA",))
        cursor.execute("SELECT id FROM brands WHERE name = ?", ("ACURA",))
        brand_id = cursor.fetchone()[0]
        print(f"Marca ACURA tiene ID: {brand_id}")

        # Insertar modelos adicionales de Acura que pueden faltar
        additional_models = [
            'CSX', 'MDX', 'RL', 'RSX', 'TL', 'TSX', 'EL', 'CL', 'NSX', 'SLX', 'INTEGRA'
        ]

        for model in additional_models:
            cursor.execute(
                "INSERT OR IGNORE INTO models (brand_id, name) VALUES (?, ?)",
                (brand_id, model)
            )
        print(f"Agregados {len(additional_models)} modelos de Acura (existentes o nuevos)")

        # Datos adicionales de años y motores para cada modelo
        acura_additional_data = [
            # 2006
            ('CSX', 2006, '2.0L L4'),
            ('MDX', 2006, '3.5L V6'),
            ('RL', 2006, '3.5L V6'),
            ('RSX', 2006, '2.0L L4'),
            ('TL', 2006, '3.2L V6'),
            ('TSX', 2006, '2.4L L4'),

            # 2005
            ('EL', 2005, '1.7L L4'),
            ('MDX', 2005, '3.5L V6'),
            ('NSX', 2005, '3.0L V6'),
            ('RSX', 2005, '3.2L V6'),
            ('RL', 2005, '3.5L V6'),
            ('RSX', 2005, '2.0L L4'),
            ('TL', 2005, '3.2L V6'),
            ('TSX', 2005, '2.4L L4'),

            # 2004
            ('EL', 2004, '1.7L L4'),
            ('MDX', 2004, '3.5L V6'),
            ('NSX', 2004, '3.0L V6'),
            ('RSX', 2004, '3.2L V6'),
            ('RL', 2004, '3.5L V6'),
            ('TL', 2004, '3.2L V6'),
            ('TSX', 2004, '2.4L L4'),

            # 2003
            ('CL', 2003, '3.2L V6'),
            ('EL', 2003, '1.7L L4'),
            ('MDX', 2003, '3.5L V6'),
            ('NSX', 2003, '3.0L V6'),
            ('RL', 2003, '3.5L V6'),
            ('RSX', 2003, '2.0L L4'),
            ('TL', 2003, '3.2L V6'),

            # 2002
            ('CL', 2002, '3.2L V6'),
            ('EL', 2002, '1.7L L4'),
            ('MDX', 2002, '3.5L V6'),
            ('NSX', 2002, '3.0L V6'),
            ('RL', 2002, '3.5L V6'),
            ('RSX', 2002, '2.0L L4'),
            ('TL', 2002, '3.2L V6'),

            # 2001
            ('CL', 2001, '3.2L V6'),
            ('EL', 2001, '1.7L L4'),
            ('INTEGRA', 2001, '1.8L L4'),
            ('MDX', 2001, '3.5L V6'),
            ('NSX', 2001, '3.0L V6'),
            ('RL', 2001, '3.5L V6'),
            ('TL', 2001, '3.2L V6'),

            # 2000
            ('EL', 2000, '1.6L L4'),
            ('INTEGRA', 2000, '1.8L L4'),
            ('NSX', 2000, '3.0L V6'),
            ('RL', 2000, '3.5L V6'),
            ('TL', 2000, '3.2L V6'),

            # 1999
            ('CL', 1999, '2.3L L4'),
            ('CL', 1999, '3.0L V6'),
            ('EL', 1999, '1.6L L4'),
            ('INTEGRA', 1999, '1.8L L4'),
            ('NSX', 1999, '3.0L V6'),
            ('RL', 1999, '3.5L V6'),
            ('SLX', 1999, '3.5L V6'),
            ('TL', 1999, '3.2L V6'),

            # 1998
            ('CL', 1998, '2.3L L4'),
            ('CL', 1998, '3.0L V6'),
            ('EL', 1998, '1.6L L4'),
            ('INTEGRA', 1998, '1.8L L4'),
            ('NSX', 1998, '3.0L V6'),
            ('RL', 1998, '3.5L V6'),
            ('SLX', 1998, '3.5L V6'),
            ('TL', 1998, '2.5L L5'),
            ('TL', 1998, '3.2L V6')
        ]

        # Insertar años adicionales
        years = list(set([data[1] for data in acura_additional_data]))  # Obtener años únicos
        for year in years:
            cursor.execute("INSERT OR IGNORE INTO years (year) VALUES (?)", (year,))
        print(f"Agregados {len(years)} años adicionales")

        # Insertar motores adicionales
        engines = list(set([data[2] for data in acura_additional_data]))  # Obtener motores únicos
        for engine in engines:
            cursor.execute("INSERT OR IGNORE INTO engines (name) VALUES (?)", (engine,))
        print(f"Agregados {len(engines)} motores adicionales")

        # Crear combinaciones modelo-año-motor adicionales
        for model_name, year, engine_name in acura_additional_data:
            # Obtener IDs
            cursor.execute("SELECT id FROM models WHERE brand_id = ? AND name = ?", (brand_id, model_name))
            model_result = cursor.fetchone()
            if model_result:
                model_id = model_result[0]
            else:
                print(f"Advertencia: Modelo {model_name} no encontrado para la marca ACURA")
                continue

            cursor.execute("SELECT id FROM years WHERE year = ?", (year,))
            year_result = cursor.fetchone()
            if year_result:
                year_id = year_result[0]
            else:
                print(f"Advertencia: Año {year} no encontrado")
                continue

            cursor.execute("SELECT id FROM engines WHERE name = ?", (engine_name,))
            engine_result = cursor.fetchone()
            if engine_result:
                engine_id = engine_result[0]
            else:
                print(f"Advertencia: Motor {engine_name} no encontrado")
                continue

            # Insertar la combinación modelo-año-motor
            cursor.execute(
                """INSERT OR REPLACE INTO model_year_engine
                   (model_id, year_id, engine_id) VALUES (?, ?, ?)""",
                (model_id, year_id, engine_id)
            )

        conn.commit()
        print(f"Se agregaron {len(acura_additional_data)} combinaciones modelo-año-motor adicionales para ACURA")
        print("Datos adicionales de ACURA agregados exitosamente a la base de datos!")

        # Mostrar algunos resultados
        print("\nAlgunos vehículos ACURA adicionales agregados:")
        cursor.execute("""
            SELECT b.name, m.name, y.year, e.name
            FROM model_year_engine mye
            JOIN models m ON mye.model_id = m.id
            JOIN brands b ON m.brand_id = b.id
            JOIN years y ON mye.year_id = y.id
            JOIN engines e ON mye.engine_id = e.id
            WHERE b.name = 'ACURA' AND y.year <= 2006
            ORDER BY m.name, y.year DESC
            LIMIT 15
        """)
        
        results = cursor.fetchall()
        for brand, model, year, engine in results:
            print(f"  {year} {brand} {model} - {engine}")

    except Exception as e:
        print(f"Error al agregar datos adicionales de ACURA: {e}")
        conn.rollback()
    finally:
        conn.close()

if __name__ == "__main__":
    add_acura_additional_data()