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

import sqlite3
import os

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

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

        # Insertar modelos de Crosley
        models = [
            'FARM-O-ROAD', 'HOT SHOT', 'PANEL DELIVERY', 'PICKUP', 
            'STANDARD', 'SUPER', 'SUPER SPORTS', 'CROSLEY'  # Agregué 'CROSLEY' porque 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 Crosley")

        # Datos de años y motores para cada modelo
        crosley_data = [
            # 1952
            ('FARM-O-ROAD', 1952, '724cc 44cid L4'),
            ('HOT SHOT', 1952, '724cc 44cid L4'),
            ('PANEL DELIVERY', 1952, '724cc 44cid L4'),
            ('PICKUP', 1952, '724cc 44cid L4'),
            ('STANDARD', 1952, '724cc 44cid L4'),
            ('SUPER', 1952, '0.7L 44cid L4'),
            ('SUPER SHOT', 1952, '0.7L 44cid L4'),
            ('SUPER SPORTS', 1952, '0.7L 44cid L4'),

            # 1951
            ('FARM-O-ROAD', 1951, '724cc 44cid L4'),
            ('HOT SHOT', 1951, '724cc 44cid L4'),
            ('PANEL DELIVERY', 1951, '724cc 44cid L4'),
            ('PICKUP', 1951, '724cc 44cid L4'),
            ('STANDARD', 1951, '724cc 44cid L4'),
            ('SUPER', 1951, '0.7L 44cid L4'),
            ('SUPER SPORTS', 1951, '0.7L 44cid L4'),

            # 1950
            ('CROSLEY', 1950, '724cc 44cid L4'),
            ('FARM-O-ROAD', 1950, '724cc 44cid L4'),
            ('HOT SHOT', 1950, '724cc 44cid L4'),
            ('PANEL DELIVERY', 1950, '724cc 44cid L4'),
            ('PICKUP', 1950, '724cc 44cid L4'),
            ('STANDARD', 1950, '724cc 44cid L4'),
            ('SUPER', 1950, '0.7L 44cid L4'),

            # 1949
            ('CROSLEY', 1949, '724cc 44cid L4'),
            ('HOT SHOT', 1949, '724cc 44cid L4'),
            ('PANEL DELIVERY', 1949, '724cc 44cid L4'),
            ('PICKUP', 1949, '724cc 44cid L4'),

            # 1948
            ('CROSLEY', 1948, '724cc 44cid L4'),
            ('PANEL DELIVERY', 1948, '724cc 44cid L4'),
            ('PICKUP', 1948, '724cc 44cid L4'),

            # 1947
            ('CROSLEY', 1947, '724cc 44cid L4'),
            ('PICKUP', 1947, '724cc 44cid L4'),

            # 1946
            ('CROSLEY', 1946, '724cc 44cid L4'),

            # 1942
            ('CROSLEY', 1942, '724cc 44cid L4'),

            # 1941
            ('CROSLEY', 1941, '579cc 35cid L2'),

            # 1940
            ('CROSLEY', 1940, '579cc 35cid L2'),

            # 1939
            ('CROSLEY', 1939, '638cc 39cid L2')
        ]

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

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

if __name__ == "__main__":
    add_crosley_data()