"""
Script to add American Motors Corporation (AMC) 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 insert_brand(conn: sqlite3.Connection, brand_name: str) -> int:
    """Insert a brand if it doesn't exist and return its ID."""
    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 insert_models(conn: sqlite3.Connection, brand_id: int, models: List[str]) -> None:
    """Insert models if they don't exist."""
    cursor = conn.cursor()

    for model_name in models:
        # 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 not result:
            # Insert new model
            cursor.execute(
                "INSERT INTO models (brand_id, name) VALUES (?, ?)",
                (brand_id, model_name)
            )

    conn.commit()


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_versions(conn: sqlite3.Connection, versions: List[Tuple]) -> None:
    """Insert vehicle versions if they don't exist."""
    cursor = conn.cursor()

    for model_name, year, engine in versions:
        # Get model ID
        cursor.execute(
            "SELECT m.id FROM models m JOIN brands ma ON m.brand_id = ma.id "
            "WHERE ma.name = 'AMERICAN MOTORS' AND m.name = ?",
            (model_name,)
        )
        model_result = cursor.fetchone()

        if model_result:
            model_id = model_result[0]

            # Get or insert year
            year_id = get_or_insert_year(conn, year)

            # Get or insert engine
            engine_id = get_or_insert_engine(conn, engine)

            # 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)
            )
            version_result = cursor.fetchone()

            if not version_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 American Motors Corporation data."""
    print("Adding American Motors Corporation data...")
    
    # Connect to database
    conn = connect_db()
    
    # Insert brand
    brand_id = insert_brand(conn, "AMERICAN MOTORS")
    print(f"Brand 'AMERICAN MOTORS' inserted with ID: {brand_id}")
    
    # Define models
    models = [
        'GREMLIN',
        'HORNET',
        'MATADOR',
        'PACER',
        'AMX',
        'CONCORD',
        'EAGLE',
        'SPIRIT'
    ]
    
    # Insert models
    insert_models(conn, brand_id, models)
    print(f"Models inserted for AMERICAN MOTORS: {', '.join(models)}")
    
    # Define versions (model, year, engine)
    versions = [
        # 1988
        ('EAGLE', 1988, '4.2L 258cid L6'),
        
        # 1987
        ('EAGLE', 1987, '4.2L 258cid L6'),
        
        # 1986
        ('EAGLE', 1986, '4.2L 258cid L6'),
        
        # 1985
        ('EAGLE', 1985, '4.2L 258cid L6'),
        
        # 1984
        ('EAGLE', 1984, '2.5L 150cid L4'),
        ('EAGLE', 1984, '4.2L 258cid L6'),
        
        # 1983
        ('CONCORD', 1983, '2.5L 151cid L4'),
        ('CONCORD', 1983, '4.2L 258cid L6'),
        ('EAGLE', 1983, '2.5L 151cid L4'),
        ('EAGLE', 1983, '4.2L 258cid L6'),
        ('SPIRIT', 1983, '2.5L 151cid L4'),
        ('SPIRIT', 1983, '4.2L 258cid L6'),
        
        # 1982
        ('CONCORD', 1982, '2.5L 151cid L4'),
        ('CONCORD', 1982, '4.2L 258cid L6'),
        ('EAGLE', 1982, '2.5L 151cid L4'),
        ('EAGLE', 1982, '4.2L 258cid L6'),
        ('SPIRIT', 1982, '2.5L 151cid L4'),
        ('SPIRIT', 1982, '4.2L 258cid L6'),
        
        # 1981
        ('CONCORD', 1981, '2.5L 151cid L4'),
        ('CONCORD', 1981, '4.2L 258cid L6'),
        ('EAGLE', 1981, '2.5L 151cid L4'),
        ('EAGLE', 1981, '4.2L 258cid L6'),
        ('SPIRIT', 1981, '2.5L 151cid L4'),
        ('SPIRIT', 1981, '4.2L 258cid L6'),
        
        # 1980
        ('AMX', 1980, '4.2L 258cid L6'),
        ('CONCORD', 1980, '2.5L 151cid L4'),
        ('CONCORD', 1980, '4.2L 258cid L6'),
        ('EAGLE', 1980, '2.5L 151cid L4'),
        ('EAGLE', 1980, '4.2L 258cid L6'),
        ('PACER', 1980, '4.2L 258cid L6'),
        ('SPIRIT', 1980, '2.5L 151cid L4'),
        ('SPIRIT', 1980, '4.2L 258cid L6'),
        
        # 1979
        ('AMX', 1979, '4.2L 258cid L6'),
        ('CONCORD', 1979, '2.0L 121cid L4'),
        ('CONCORD', 1979, '3.8L 232cid L6'),
        ('CONCORD', 1979, '4.2L 258cid L6'),
        ('EAGLE', 1979, '2.5L 151cid L4'),
        ('EAGLE', 1979, '4.2L 258cid L6'),
        ('PACER', 1979, '4.2L 258cid L6'),
        ('SPIRIT', 1979, '2.5L 151cid L4'),
        ('SPIRIT', 1979, '4.2L 258cid L6'),
        
        # 1978
        ('AMX', 1978, '4.2L 258cid L6'),
        ('CONCORD', 1978, '2.0L 121cid L4'),
        ('CONCORD', 1978, '3.8L 232cid L6'),
        ('CONCORD', 1978, '4.2L 258cid L6'),
        ('EAGLE', 1978, '2.5L 151cid L4'),
        ('EAGLE', 1978, '4.2L 258cid L6'),
        ('PACER', 1978, '4.2L 258cid L6'),
        ('SPIRIT', 1978, '2.5L 151cid L4'),
        ('SPIRIT', 1978, '4.2L 258cid L6'),
        
        # 1977
        ('GREMLIN', 1977, '2.0L 121cid L4'),
        ('GREMLIN', 1977, '3.8L 232cid L6'),
        ('GREMLIN', 1977, '4.2L 258cid L6'),
        ('HORNET', 1977, '3.8L 232cid L6'),
        ('HORNET', 1977, '4.2L 258cid L6'),
        ('HORNET', 1977, '5.0L 304cid V8'),
        ('MATADOR', 1977, '4.2L 258cid L6'),
        ('MATADOR', 1977, '5.0L 304cid V8'),
        ('MATADOR', 1977, '5.9L 360cid V8'),
        ('PACER', 1977, '3.8L 232cid L6'),
        ('PACER', 1977, '4.2L 258cid L6'),
        
        # 1976
        ('GREMLIN', 1976, '3.8L 232cid L6'),
        ('GREMLIN', 1976, '4.2L 258cid L6'),
        ('GREMLIN', 1976, '5.0L 304cid V8'),
        ('HORNET', 1976, '3.8L 232cid L6'),
        ('HORNET', 1976, '4.2L 258cid L6'),
        ('HORNET', 1976, '5.0L 304cid V8'),
        ('MATADOR', 1976, '4.2L 258cid L6'),
        ('MATADOR', 1976, '5.0L 304cid V8'),
        ('MATADOR', 1976, '5.9L 360cid V8'),
        ('PACER', 1976, '3.8L 232cid L6'),
        ('PACER', 1976, '4.2L 258cid L6'),
        
        # 1975
        ('GREMLIN', 1975, '3.8L 232cid L6'),
        ('GREMLIN', 1975, '4.2L 258cid L6'),
        ('GREMLIN', 1975, '5.0L 304cid V8'),
        ('HORNET', 1975, '3.8L 232cid L6'),
        ('HORNET', 1975, '4.2L 258cid L6'),
        ('HORNET', 1975, '5.0L 304cid V8'),
        ('MATADOR', 1975, '4.2L 258cid L6'),
        ('MATADOR', 1975, '5.0L 304cid V8'),
        ('MATADOR', 1975, '5.9L 360cid V8'),
        ('PACER', 1975, '3.8L 232cid L6'),
        ('PACER', 1975, '4.2L 258cid L6')
    ]
    
    # Insert versions
    insert_versions(conn, versions)
    print(f"Inserted {len(versions)} versions for AMERICAN MOTORS vehicles")
    
    # Close connection
    conn.close()
    print("American Motors Corporation data added successfully!")


if __name__ == "__main__":
    main()