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

import sqlite3
import os

def add_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 de varias marcas a la base de datos...")

    try:
        # Insertar marcas
        brands = ['CONTINENTAL', 'CORD', 'COLE', 'CLEVELAND', 'CISITALIA', 'CHIREY']
        for brand in brands:
            cursor.execute("INSERT OR IGNORE INTO brands (name) VALUES (?)", (brand,))
        
        print(f"Agregadas {len(brands)} marcas históricas")

        # Insertar modelos por marca
        # CONTINENTAL
        continental_models = ['BEACON', 'ACE', 'FLYER']
        for model in continental_models:
            cursor.execute("SELECT id FROM brands WHERE name = ?", ("CONTINENTAL",))
            brand_id = cursor.fetchone()[0]
            cursor.execute(
                "INSERT OR IGNORE INTO models (brand_id, name) VALUES (?, ?)",
                (brand_id, model)
            )

        # CORD
        cord_models = ['L-29', '810', '812']
        for model in cord_models:
            cursor.execute("SELECT id FROM brands WHERE name = ?", ("CORD",))
            brand_id = cursor.fetchone()[0]
            cursor.execute(
                "INSERT OR IGNORE INTO models (brand_id, name) VALUES (?, ?)",
                (brand_id, model)
            )

        # COLE
        cole_models = ['SERIES 890', 'AERO EIGHT', 'SERIES 870', '8-50', '4-40', '6-50', '6-60', 
                       'FOUR', 'SIX', 'FIFTY', 'FORTY', 'SIXTY', 'MODEL 30']
        for model in cole_models:
            cursor.execute("SELECT id FROM brands WHERE name = ?", ("COLE",))
            brand_id = cursor.fetchone()[0]
            cursor.execute(
                "INSERT OR IGNORE INTO models (brand_id, name) VALUES (?, ?)",
                (brand_id, model)
            )

        # CLEVELAND
        cleveland_models = ['MODEL 31', 'MODEL 43', 'MODEL 42', 'MODEL 41', 'MODEL 40']
        for model in cleveland_models:
            cursor.execute("SELECT id FROM brands WHERE name = ?", ("CLEVELAND",))
            brand_id = cursor.fetchone()[0]
            cursor.execute(
                "INSERT OR IGNORE INTO models (brand_id, name) VALUES (?, ?)",
                (brand_id, model)
            )

        # CISITALIA
        cisitalia_models = ['202']
        for model in cisitalia_models:
            cursor.execute("SELECT id FROM brands WHERE name = ?", ("CISITALIA",))
            brand_id = cursor.fetchone()[0]
            cursor.execute(
                "INSERT OR IGNORE INTO models (brand_id, name) VALUES (?, ?)",
                (brand_id, model)
            )

        # CHIREY
        chirey_models = ['ARRIZO 8', 'TIGGO 4PRO', 'TIGGO 7PRO', 'TIGGO 8PRO', 'OMODA 5']
        for model in chirey_models:
            cursor.execute("SELECT id FROM brands WHERE name = ?", ("CHIREY",))
            brand_id = cursor.fetchone()[0]
            cursor.execute(
                "INSERT OR IGNORE INTO models (brand_id, name) VALUES (?, ?)",
                (brand_id, model)
            )

        print("Agregados modelos para todas las marcas")

        # Datos históricos de años y motores para cada marca
        historical_data = [
            # CONTINENTAL
            ('CONTINENTAL', 'BEACON', 1934, '4cyl'),
            ('CONTINENTAL', 'ACE', 1933, '6cyl'),
            ('CONTINENTAL', 'BEACON', 1933, '4cyl'),
            ('CONTINENTAL', 'FLYER', 1933, '6cyl'),

            # CORD
            ('CORD', 'L-29', 1933, '4.7L 289cid V8'),
            ('CORD', '812', 1936, '4.7L 289cid V8'),
            ('CORD', '810', 1936, '4.7L 289cid V8'),
            ('CORD', '812', 1936, '8cyl'),
            ('CORD', 'L-29', 1932, '4.9L 298cid L8'),
            ('CORD', 'L-29', 1931, '4.9L 298cid L8'),
            ('CORD', 'L-29', 1930, '4.9L 298cid L8'),
            ('CORD', 'L-29', 1929, '8cyl'),

            # COLE
            ('COLE', 'SERIES 890', 1925, '8cyl'),
            ('COLE', 'SERIES 890', 1924, '8cyl'),
            ('COLE', 'SERIES 890', 1923, '8cyl'),
            ('COLE', 'AERO EIGHT', 1922, '8cyl'),
            ('COLE', 'AERO EIGHT', 1921, '8cyl'),
            ('COLE', 'AERO EIGHT', 1920, '8cyl'),
            ('COLE', 'SERIES 870', 1919, '8cyl'),
            ('COLE', 'SERIES 870', 1918, '8cyl'),
            ('COLE', '8-50', 1916, '8cyl'),
            ('COLE', '4-40', 1915, '4cyl'),
            ('COLE', '6-50', 1915, '6cyl'),
            ('COLE', '6-60', 1915, '6cyl'),
            ('COLE', 'FOUR', 1914, '4cyl'),
            ('COLE', 'SIX', 1914, '6cyl'),
            ('COLE', 'FIFTY', 1913, '4cyl'),
            ('COLE', 'FORTY', 1913, '4cyl'),
            ('COLE', 'SIXTY', 1913, '6cyl'),
            ('COLE', 'FORTY', 1912, '4cyl'),
            ('COLE', 'MODEL 30', 1911, '4cyl'),
            ('COLE', 'MODEL 30', 1910, '4cyl'),

            # CLEVELAND
            ('CLEVELAND', 'MODEL 31', 1926, '6cyl'),
            ('CLEVELAND', 'MODEL 43', 1926, '6cyl'),
            ('CLEVELAND', 'MODEL 31', 1925, '6cyl'),
            ('CLEVELAND', 'MODEL 43', 1925, '6cyl'),
            ('CLEVELAND', 'MODEL 42', 1924, '6cyl'),
            ('CLEVELAND', 'MODEL 42', 1923, '6cyl'),
            ('CLEVELAND', 'MODEL 41', 1922, '6cyl'),
            ('CLEVELAND', 'MODEL 41', 1921, '6cyl'),
            ('CLEVELAND', 'MODEL 40', 1920, '6cyl'),
            ('CLEVELAND', 'MODEL 40', 1919, '6cyl'),

            # CISITALIA
            ('CISITALIA', '202', 1952, '1.1L L4'),
            ('CISITALIA', '202', 1951, '1.1L L4'),
            ('CISITALIA', '202', 1950, '1.1L L4'),
            ('CISITALIA', '202', 1949, '1.1L 66cid L4'),
            ('CISITALIA', '202', 1948, '1.1L 66cid L4'),
            ('CISITALIA', '202', 1947, '1.1L 66cid L4'),

            # CHIREY
            ('CHIREY', 'ARRIZO 8', 2025, '1.6L L4 Turbocharged'),
            ('CHIREY', 'TIGGO 4PRO', 2025, '1.5L L4 Turbocharged'),
            ('CHIREY', 'TIGGO 7PRO', 2025, '1.5L L4 Turbocharged'),
            ('CHIREY', 'TIGGO 8PRO', 2025, '1.6L L4 Turbocharged'),
            ('CHIREY', 'ARRIZO 8', 2024, '1.6L L4 Turbocharged'),
            ('CHIREY', 'TIGGO 4PRO', 2024, '1.5L L4 Turbocharged'),
            ('CHIREY', 'TIGGO 7PRO', 2024, '1.5L L4 ELECTRIC/GAS Turbocharged'),
            ('CHIREY', 'TIGGO 7PRO', 2024, '1.5L L4 Turbocharged'),
            ('CHIREY', 'TIGGO 8PRO', 2024, '1.6L L4 Turbocharged'),
            ('CHIREY', 'TIGGO 8PRO', 2024, '1.5L L4 ELECTRIC/GAS Turbocharged'),
            ('CHIREY', 'TIGGO 8PRO', 2024, '2.0L L4 Turbocharged'),
            ('CHIREY', 'OMODA 5', 2023, '1.5L L4'),
            ('CHIREY', 'TIGGO 4PRO', 2023, '1.5L L4'),
            ('CHIREY', 'TIGGO 7PRO', 2023, '1.5L L4'),
            ('CHIREY', 'TIGGO 8PRO', 2023, '1.5L L4 ELECTRIC/GAS Turbocharged'),
            ('CHIREY', 'TIGGO 8PRO', 2023, '1.6L L4 Turbocharged'),
            ('CHIREY', 'TIGGO 8PRO', 2023, '2.0L L4 Turbocharged')
        ]

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

        # Insertar motores
        engines = list(set([data[3] for data in 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")

        # Crear combinaciones modelo-año-motor
        for brand_name, model_name, year, engine_name in historical_data:
            # Obtener IDs
            cursor.execute("SELECT id FROM brands WHERE name = ?", (brand_name,))
            brand_result = cursor.fetchone()
            if brand_result:
                brand_id = brand_result[0]
            else:
                print(f"Advertencia: Marca {brand_name} no encontrada")
                continue

            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 {brand_name}")
                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(historical_data)} combinaciones modelo-año-motor históricas")
        print("Datos históricos agregados exitosamente a la base de datos!")

        # Mostrar algunos resultados
        print("\nAlgunos vehículos históricos 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
            ORDER BY y.year DESC
            LIMIT 20
        """)
        
        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: {e}")
        conn.rollback()
    finally:
        conn.close()

if __name__ == "__main__":
    add_historical_data()