#!/usr/bin/env python3
"""Apply migration 015: Add utilisation 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", "015_add_utilisation.sql")

def apply_migration():
    """Apply migration 015"""
    print("Applying migration 015: Add utilisation 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 015 applied successfully")

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

        if utilisation_col:
            print(f"✅ Column 'utilisation' added: {utilisation_col[0]}")
        else:
            print("⚠️  Warning: Column 'utilisation' 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()
