#!/usr/bin/env python3
"""Apply migration 014: Add pci_slot field"""

import sqlite3
import os

DB_PATH = os.path.join(os.path.dirname(__file__), "data", "peripherals.db")
MIGRATION_FILE = os.path.join(os.path.dirname(__file__), "migrations", "014_add_pci_slot.sql")

def apply_migration():
    """Apply migration 014"""
    print("Applying migration 014: Add pci_slot field...")

    # Read migration SQL
    with open(MIGRATION_FILE, 'r') as f:
        migration_sql = f.read()

    # Connect to database
    conn = sqlite3.connect(DB_PATH)
    cursor = conn.cursor()

    try:
        # Execute migration
        cursor.executescript(migration_sql)
        conn.commit()
        print("✅ Migration 014 applied successfully")

        # Verify the column was added
        cursor.execute("PRAGMA table_info(peripherals)")
        columns = cursor.fetchall()
        pci_slot_col = [col for col in columns if col[1] == 'pci_slot']

        if pci_slot_col:
            print(f"✅ Column 'pci_slot' added: {pci_slot_col[0]}")
        else:
            print("⚠️  Warning: Column 'pci_slot' not found after migration")

    except sqlite3.Error as e:
        if "duplicate column name" in str(e).lower():
            print("ℹ️  Migration already applied (column exists)")
        else:
            print(f"❌ Error applying migration: {e}")
            conn.rollback()
            raise
    finally:
        conn.close()

if __name__ == "__main__":
    apply_migration()
