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

import sqlite3
import os

def add_ac_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 AC a la base de datos...")

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

        # Insertar modelos de AC
        models = [
            '428', 'ACE', 'ACECA', 'GREYHOUND', 'TWO-LITRE'
        ]

        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 AC")

        # Datos de años y motores para cada modelo
        ac_data = [
            # 428
            ('428', 1973, '7.0L V8'),
            ('428', 1972, '7.0L V8'),
            ('428', 1971, '7.0L V8'),
            ('428', 1970, '7.0L V8'),
            ('428', 1969, '7.0L V8'),
            ('428', 1968, '7.0L V8'),
            ('428', 1967, '7.0L V8'),

            # ACE
            ('ACE', 1963, '2.0L L6'),
            ('ACE', 1963, '2.6L L6'),
            ('ACE', 1962, '2.0L L6'),
            ('ACE', 1962, '2.6L L6'),
            ('ACE', 1961, '2.0L L6'),
            ('ACE', 1961, '2.6L L6'),
            ('ACE', 1960, '2.0L L6'),
            ('ACE', 1960, '2.6L L6'),
            ('ACE', 1959, '2.0L L6'),
            ('ACE', 1958, '2.0L L6'),
            ('ACE', 1957, '2.0L L6'),
            ('ACE', 1956, '2.0L L6'),
            ('ACE', 1955, '2.0L L6'),
            ('ACE', 1954, '2.0L L6'),
            ('ACE', 1953, '2.0L L6'),

            # ACECA
            ('ACECA', 1963, '2.0L L6'),
            ('ACECA', 1963, '2.6L L6'),
            ('ACECA', 1962, '2.0L L6'),
            ('ACECA', 1962, '2.6L L6'),
            ('ACECA', 1961, '2.0L L6'),
            ('ACECA', 1961, '2.6L L6'),
            ('ACECA', 1960, '2.0L L6'),
            ('ACECA', 1960, '2.6L L6'),
            ('ACECA', 1958, '2.0L L6'),
            ('ACECA', 1957, '2.0L L6'),
            ('ACECA', 1956, '2.0L L6'),
            ('ACECA', 1955, '2.0L L6'),

            # GREYHOUND
            ('GREYHOUND', 1963, '2.0L L6'),
            ('GREYHOUND', 1962, '2.0L L6'),
            ('GREYHOUND', 1961, '2.0L L6'),
            ('GREYHOUND', 1960, '2.0L L6'),

            # TWO-LITRE
            ('TWO-LITRE', 1958, '2.0L L6'),
            ('TWO-LITRE', 1957, '2.0L L6'),
            ('TWO-LITRE', 1956, '2.0L L6'),
            ('TWO-LITRE', 1955, '2.0L L6'),
            ('TWO-LITRE', 1954, '2.0L L6'),
            ('TWO-LITRE', 1953, '2.0L L6'),
            ('TWO-LITRE', 1952, '2.0L L6'),
            ('TWO-LITRE', 1951, '2.0L L6'),
            ('TWO-LITRE', 1950, '2.0L L6'),
            ('TWO-LITRE', 1949, '2.0L 122cid L6'),
            ('TWO-LITRE', 1948, '2.0L 122cid L6'),
            ('TWO-LITRE', 1947, '2.0L 122cid L6'),
        ]

        # Insertar años
        years = list(set([data[1] for data in ac_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 ac_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 ac_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 AC")
                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(ac_data)} combinaciones modelo-año-motor para AC")
        print("Datos de AC agregados exitosamente a la base de datos!")

        # Mostrar algunos resultados
        print("\nAlgunos vehículos AC 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 = 'AC'
            ORDER BY m.name, y.year DESC
            LIMIT 10
        """)
        
        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 AC: {e}")
        conn.rollback()
    finally:
        conn.close()

if __name__ == "__main__":
    add_ac_data()