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

import sqlite3
import os

def add_alfa_romeo_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 de Alfa Romeo a la base de datos...")

    try:
        # Insertar la marca Alfa Romeo
        cursor.execute("INSERT OR IGNORE INTO brands (name) VALUES (?)", ("ALFA ROMEO",))
        cursor.execute("SELECT id FROM brands WHERE name = ?", ("ALFA ROMEO",))
        brand_id = cursor.fetchone()[0]
        print(f"Marca ALFA ROMEO tiene ID: {brand_id}")

        # Insertar modelos de Alfa Romeo (incluyendo GIULIA que aparece en los datos)
        models = [
            '4C', 'GIULIETTA', 'MITO', '159', '8C', 'BRERA', 'GT', 'SPIDER', 
            '147', '156', '166', 'SPORTWAGON', '164', 'MILANO', 'GTV-6', 
            'STELVIO', 'TONALE', 'GIULIA'  # Agregué GIULIA que aparece en los datos
        ]

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

        # Datos de años y motores para cada modelo
        alfa_data = [
            # 2025
            ('GIULIA', 2025, '2.0L L4 Turbocharged'),
            ('STELVIO', 2025, '2.0L L4 Turbocharged'),
            ('TONALE', 2025, '1.3L L4 ELECTRIC/GAS Turbocharged SOHC'),
            ('TONALE', 2025, '2.0L L4 Turbocharged'),

            # 2024
            ('GIULIA', 2024, '2.0L L4 Turbocharged'),
            ('STELVIO', 2024, '2.0L L4 Turbocharged'),
            ('TONALE', 2024, '1.3L L4 ELECTRIC/GAS Turbocharged'),
            ('TONALE', 2024, '2.0L L4 Turbocharged'),

            # 2023
            ('GIULIA', 2023, '2.0L L4 Turbocharged'),
            ('STELVIO', 2023, '2.0L L4 Turbocharged'),
            ('STELVIO', 2023, '2.9L V6 Turbocharged'),

            # 2022
            ('GIULIA', 2022, '2.0L L4 Turbocharged'),
            ('STELVIO', 2022, '2.0L L4 Turbocharged'),
            ('STELVIO', 2022, '2.9L V6 Turbocharged'),

            # 2021
            ('GIULIA', 2021, '2.0L L4 Turbocharged'),
            ('GIULIA', 2021, '2.9L V6 Turbocharged'),
            ('GIULIETTA', 2021, '1.7L L4 Turbocharged'),
            ('STELVIO', 2021, '2.0L L4 Turbocharged'),
            ('STELVIO', 2021, '2.9L V6 Turbocharged'),

            # 2020
            ('4C', 2020, '1.7L L4 Turbocharged'),
            ('GIULIA', 2020, '2.0L L4 Turbocharged'),
            ('GIULIA', 2020, '2.9L V6 Turbocharged'),
            ('GIULIETTA', 2020, '1.7L L4 Turbocharged'),
            ('STELVIO', 2020, '2.0L L4 Turbocharged'),
            ('STELVIO', 2020, '2.9L V6 Turbocharged'),

            # 2019
            ('4C', 2019, '1.7L L4 Turbocharged'),
            ('GIULIA', 2019, '2.0L L4 Turbocharged'),
            ('GIULIA', 2019, '2.9L V6 Turbocharged'),
            ('GIULIETTA', 2019, '1.7L L4 Turbocharged'),
            ('MITO', 2019, '1.4L L4 Turbocharged'),
            ('STELVIO', 2019, '2.0L L4 Turbocharged'),
            ('STELVIO', 2019, '2.9L V6 Turbocharged'),

            # 2018
            ('4C', 2018, '1.7L L4 Turbocharged'),
            ('GIULIA', 2018, '2.0L L4 Turbocharged'),
            ('GIULIA', 2018, '2.9L V6 Turbocharged'),
            ('GIULIETTA', 2018, '1.7L L4 Turbocharged'),
            ('MITO', 2018, '1.4L L4 Turbocharged'),
            ('STELVIO', 2018, '2.0L L4 Turbocharged'),
            ('STELVIO', 2018, '2.9L V6 Turbocharged'),

            # 2017
            ('4C', 2017, '1.7L L4 Turbocharged'),
            ('GIULIA', 2017, '2.0L L4 Turbocharged'),
            ('GIULIA', 2017, '2.9L V6 Turbocharged'),
            ('GIULIETTA', 2017, '1.7L L4 Turbocharged'),
            ('MITO', 2017, '1.4L L4 Turbocharged'),
            ('STELVIO', 2017, '2.0L L4 Turbocharged'),
            ('STELVIO', 2017, '2.9L V6 Turbocharged'),

            # 2016
            ('4C', 2016, '1.7L L4 Turbocharged'),
            ('GIULIA', 2016, '2.0L L4 Turbocharged'),
            ('GIULIA', 2016, '2.9L V6 Turbocharged'),
            ('GIULIETTA', 2016, '1.7L L4 Turbocharged'),
            ('MITO', 2016, '1.4L L4 Turbocharged'),
            ('STELVIO', 2016, '2.0L L4 Turbocharged'),
            ('STELVIO', 2016, '2.9L V6 Turbocharged'),

            # 2015
            ('4C', 2015, '1.7L L4 Turbocharged'),
            ('GIULIETTA', 2015, '1.7L L4 Turbocharged'),
            ('GIULIETTA', 2015, '1.8L L4 Turbocharged'),
            ('MITO', 2015, '1.4L L4 Turbocharged'),

            # 2014
            ('GIULIETTA', 2014, '1.7L L4 Turbocharged'),

            # 2013
            ('GIULIETTA', 2013, '1.7L L4 Turbocharged'),
            ('MITO', 2013, '1.4L L4 Turbocharged'),

            # 2012
            ('159', 2012, '2.2L L4'),
            ('159', 2012, '3.2L V6'),
            ('GIULIETTA', 2012, '1.8L L4 Turbocharged'),
            ('MITO', 2012, '1.4L L4 Turbocharged'),

            # 2008
            ('159', 2008, '2.2L L4'),
            ('8C', 2008, '4.7L V8'),
            ('BRERA', 2008, '3.2L V6'),
            ('GT', 2008, '2.0L L4'),
            ('SPIDER', 2008, '3.2L V6'),

            # 2007
            ('147', 2007, '2.0L L4'),
            ('159', 2007, '2.2L L4'),
            ('159', 2007, '3.2L V6'),
            ('BRERA', 2007, '3.2L V6'),
            ('GT', 2007, '2.0L L4'),
            ('SPIDER', 2007, '3.2L V6'),

            # 2005
            ('147', 2005, '2.0L L4'),

            # 2004
            ('147', 2004, '2.0L L4'),

            # 2003
            ('147', 2003, '2.0L L4'),
            ('166', 2003, '3.0L V6'),
            ('GTV', 2003, '3.0L V6'),  # Nota: En los datos originales dice 'GTV', pero en modelos dice 'GTV-6'
            ('SPIDER', 2003, '3.0L V6'),

            # 2002
            ('147', 2002, '2.0L L4'),
            ('156', 2002, '2.0L L4'),
            ('166', 2002, '3.0L V6'),
            ('SPORTWAGON', 2002, '2.0L L4'),

            # 1995
            ('164', 1995, '3.0L V6'),

            # 1994
            ('164', 1994, '3.0L V6'),
            ('SPIDER', 1994, '2.0L L4'),

            # 1993
            ('164', 1993, '3.0L V6'),
            ('SPIDER', 1993, '2.0L L4'),

            # 1992
            ('164', 1992, '3.0L V6'),
            ('SPIDER', 1992, '2.0L L4'),

            # 1991
            ('164', 1991, '2.0L L4'),

            # 1990
            ('SPIDER', 1990, '2.0L L4'),

            # 1989
            ('MILANO', 1989, '2.5L V6'),
            ('MILANO', 1989, '3.0L V6'),
            ('SPIDER', 1989, '2.0L L4'),

            # 1988
            ('MILANO', 1988, '2.5L V6'),
            ('MILANO', 1988, '3.0L V6'),
            ('SPIDER', 1988, '2.0L L4'),

            # 1987
            ('MILANO', 1987, '2.5L V6'),
            ('MILANO', 1987, '3.0L V6'),
            ('SPIDER', 1987, '2.0L L4'),

            # 1986
            ('GTV-6', 1986, '2.5L V6'),
            ('SPIDER', 1986, '2.0L L4'),

            # 1985
            ('GTV-6', 1985, '2.5L V6'),
            ('SPIDER', 1985, '2.0L L4'),

            # 1984
            ('GTV-6', 1984, '2.5L V6'),
            ('SPIDER', 1984, '2.0L L4'),

            # 1983
            ('GTV-6', 1983, '2.5L V6'),
            ('SPIDER', 1983, '2.0L L4'),

            # 1982
            ('GTV-6', 1982, '2.5L V6'),
            ('SPIDER', 1982, '2.0L L4'),

            # 1981
            ('GTV-6', 1981, '2.5L V6'),
            ('SPIDER', 1981, '2.0L L4'),

            # 1980
            ('SPIDER', 1980, '2.0L L4')
        ]

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

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

        # Crear combinaciones modelo-año-motor
        for model_name, year, engine_name in alfa_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 ALFA ROMEO")
                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(alfa_data)} combinaciones modelo-año-motor para ALFA ROMEO")
        print("Datos de ALFA ROMEO agregados exitosamente a la base de datos!")

        # Mostrar algunos resultados
        print("\nAlgunos vehículos ALFA ROMEO 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 = 'ALFA ROMEO'
            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 de ALFA ROMEO: {e}")
        conn.rollback()
    finally:
        conn.close()

if __name__ == "__main__":
    add_alfa_romeo_data()