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

import sqlite3
import os

def add_acura_historical_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 históricos 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
        additional_models = ['CL', 'INTEGRA', 'NSX', 'RL', 'SLX', 'TL', 'LEGEND', 'VIGOR']

        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 adicionales de Acura")

        # Datos históricos de años y motores para cada modelo
        acura_historical_data = [
            # 1997
            ('CL', 1997, '2.2L L4'),
            ('CL', 1997, '3.0L V6'),
            ('INTEGRA', 1997, '1.8L L4'),
            ('NSX', 1997, '3.0L V6'),
            ('NSX', 1997, '3.2L V6'),
            ('RL', 1997, '3.5L V6'),
            ('SLX', 1997, '3.2L V6'),
            ('TL', 1997, '2.5L L5'),
            ('TL', 1997, '3.2L V6'),

            # 1996
            ('INTEGRA', 1996, '1.8L L4'),
            ('NSX', 1996, '3.0L V6'),
            ('RL', 1996, '3.5L V6'),
            ('SLX', 1996, '3.2L V6'),
            ('TL', 1996, '2.5L L5'),
            ('TL', 1996, '3.2L V6'),

            # 1995
            ('INTEGRA', 1995, '1.8L L4'),
            ('LEGEND', 1995, '3.2L V6'),
            ('NSX', 1995, '3.0L V6'),
            ('TL', 1995, '2.5L L5'),

            # 1994
            ('INTEGRA', 1994, '1.8L L4'),
            ('LEGEND', 1994, '3.2L V6'),
            ('NSX', 1994, '3.0L V6'),
            ('VIGOR', 1994, '2.5L L5'),

            # 1993
            ('INTEGRA', 1993, '1.7L L4'),
            ('INTEGRA', 1993, '1.8L L4'),
            ('LEGEND', 1993, '3.2L V6'),
            ('NSX', 1993, '3.0L V6'),
            ('VIGOR', 1993, '2.5L L5'),

            # 1992
            ('INTEGRA', 1992, '1.7L L4'),
            ('INTEGRA', 1992, '1.8L L4'),
            ('LEGEND', 1992, '3.2L V6'),
            ('NSX', 1992, '3.0L V6'),
            ('VIGOR', 1992, '2.5L L5'),

            # 1991
            ('INTEGRA', 1991, '1.8L L4'),
            ('LEGEND', 1991, '3.2L V6'),
            ('NSX', 1991, '3.0L V6'),

            # 1990
            ('INTEGRA', 1990, '1.8L L4'),
            ('LEGEND', 1990, '2.7L V6'),

            # 1989
            ('INTEGRA', 1989, '1.6L L4'),
            ('LEGEND', 1989, '2.7L V6'),

            # 1988
            ('INTEGRA', 1988, '1.6L L4'),
            ('LEGEND', 1988, '2.7L V6'),

            # 1987
            ('INTEGRA', 1987, '1.6L L4'),
            ('LEGEND', 1987, '2.5L V6'),
            ('LEGEND', 1987, '2.7L V6'),

            # 1986
            ('INTEGRA', 1986, '1.6L L4'),
            ('LEGEND', 1986, '2.5L V6'),
            ('LEGEND', 1986, '2.7L V6')
        ]

        # Insertar años históricos
        years = list(set([data[1] for data in acura_historical_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 históricos adicionales")

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

        # Crear combinaciones modelo-año-motor históricas
        for model_name, year, engine_name in acura_historical_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_historical_data)} combinaciones modelo-año-motor históricas adicionales para ACURA")
        print("Datos históricos adicionales de ACURA agregados exitosamente a la base de datos!")

        # Mostrar algunos resultados
        print("\nAlgunos vehículos ACURA históricos 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 BETWEEN 1986 AND 1997
            ORDER BY y.year DESC, m.name
            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 históricos adicionales de ACURA: {e}")
        conn.rollback()
    finally:
        conn.close()

if __name__ == "__main__":
    add_acura_historical_data()