"""
Script to add Asuna vehicle data to the database.
This includes inserting the brand, models, and year/motor combinations.
"""
import sqlite3
from typing import List, Tuple


def connect_db(db_path: str = "vehicle_database/vehicle_database.db") -> sqlite3.Connection:
    """Connect to the vehicle database."""
    conn = sqlite3.connect(db_path)
    conn.execute("PRAGMA foreign_keys = ON")  # Enable foreign key constraints
    return conn


def get_or_insert_brand(conn: sqlite3.Connection, brand_name: str) -> int:
    """Get brand ID or insert if it doesn't exist."""
    cursor = conn.cursor()
    
    # Check if brand already exists
    cursor.execute("SELECT id FROM brands WHERE name = ?", (brand_name,))
    result = cursor.fetchone()
    
    if result:
        return result[0]  # Return existing ID
    
    # Insert new brand
    cursor.execute("INSERT INTO brands (name) VALUES (?)", (brand_name,))
    conn.commit()
    return cursor.lastrowid


def get_or_insert_model(conn: sqlite3.Connection, brand_id: int, model_name: str) -> int:
    """Get model ID or insert if it doesn't exist."""
    cursor = conn.cursor()
    
    # Check if model already exists for this brand
    cursor.execute(
        "SELECT id FROM models WHERE brand_id = ? AND name = ?", 
        (brand_id, model_name)
    )
    result = cursor.fetchone()
    
    if result:
        return result[0]  # Return existing ID
    
    # Insert new model
    cursor.execute(
        "INSERT INTO models (brand_id, name) VALUES (?, ?)", 
        (brand_id, model_name)
    )
    conn.commit()
    return cursor.lastrowid


def get_or_insert_engine(conn: sqlite3.Connection, engine_name: str) -> int:
    """Get engine ID or insert if it doesn't exist."""
    cursor = conn.cursor()
    
    # Check if engine already exists
    cursor.execute("SELECT id FROM engines WHERE name = ?", (engine_name,))
    result = cursor.fetchone()
    
    if result:
        return result[0]  # Return existing ID
    
    # Insert new engine
    cursor.execute("INSERT INTO engines (name) VALUES (?)", (engine_name,))
    conn.commit()
    return cursor.lastrowid


def get_or_insert_year(conn: sqlite3.Connection, year: int) -> int:
    """Get year ID or insert if it doesn't exist."""
    cursor = conn.cursor()
    
    # Check if year already exists
    cursor.execute("SELECT id FROM years WHERE year = ?", (year,))
    result = cursor.fetchone()
    
    if result:
        return result[0]  # Return existing ID
    
    # Insert new year
    cursor.execute("INSERT INTO years (year) VALUES (?)", (year,))
    conn.commit()
    return cursor.lastrowid


def insert_version_relationship(conn: sqlite3.Connection, model_id: int, year_id: int, engine_id: int) -> None:
    """Insert a version relationship if it doesn't exist."""
    cursor = conn.cursor()
    
    # Check if version relationship already exists
    cursor.execute(
        "SELECT id FROM model_year_engine WHERE model_id = ? AND year_id = ? AND engine_id = ?", 
        (model_id, year_id, engine_id)
    )
    result = cursor.fetchone()
    
    if not result:
        # Insert new version relationship
        cursor.execute(
            "INSERT INTO model_year_engine (model_id, year_id, engine_id) VALUES (?, ?, ?)", 
            (model_id, year_id, engine_id)
        )
        conn.commit()


def main():
    """Main function to add Asuna data."""
    print("Adding Asuna data...")
    
    # Connect to database
    conn = connect_db()
    
    # Insert brand
    brand_id = get_or_insert_brand(conn, "ASUNA")
    print(f"Brand 'ASUNA' inserted with ID: {brand_id}")
    
    # Define models
    models = [
        'SUNRUNNER',
        'GT',
        'SE',
        'SUNFIRE'
    ]
    
    # Insert models
    for model_name in models:
        model_id = get_or_insert_model(conn, brand_id, model_name)
    print(f"Models inserted for ASUNA: {', '.join(models)}")
    
    # Define versions (model, year, engine)
    versions = [
        # 1995
        ('SUNRUNNER', 1995, '1.6L L4'),

        # 1994
        ('SUNRUNNER', 1994, '1.6L L4'),

        # 1993
        ('GT', 1993, '1.6L L4'),
        ('SE', 1993, '1.6L L4'),
        ('SUNFIRE', 1993, '1.8L L4'),
        ('SUNRUNNER', 1993, '1.6L L4'),

        # 1992
        ('SUNRUNNER', 1992, '1.6L L4')
    ]
    
    # Insert version relationships
    for model_name, year, engine in versions:
        model_id = get_or_insert_model(conn, brand_id, model_name)
        year_id = get_or_insert_year(conn, year)
        engine_id = get_or_insert_engine(conn, engine)
        insert_version_relationship(conn, model_id, year_id, engine_id)
    
    print(f"Inserted {len(versions)} version relationships for ASUNA vehicles")
    
    # Close connection
    conn.close()
    print("Asuna data added successfully!")


if __name__ == "__main__":
    main()