#!/usr/bin/env python3
"""
Apply migration 008: Add specifications and notes fields
"""
import sqlite3
from pathlib import Path

# Database path
DB_PATH = Path(__file__).parent / "data" / "peripherals.db"
MIGRATION_FILE = Path(__file__).parent / "migrations" / "008_add_specifications_notes.sql"

def apply_migration():
    """Apply migration 008"""
    print(f"Applying migration 008 to {DB_PATH}")

    if not DB_PATH.exists():
        print(f"❌ Database not found: {DB_PATH}")
        return False

    if not MIGRATION_FILE.exists():
        print(f"❌ Migration file not found: {MIGRATION_FILE}")
        return False

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

    # Connect and execute
    conn = sqlite3.connect(DB_PATH)
    cursor = conn.cursor()

    try:
        # Split by semicolon and execute each statement
        statements = [s.strip() for s in migration_sql.split(';') if s.strip() and not s.strip().startswith('--')]

        for statement in statements:
            if statement:
                cursor.execute(statement)

        conn.commit()
        print("✅ Migration 008 applied successfully")
        print("   - Added specifications column")
        print("   - Added notes column")

        # Verify columns exist
        cursor.execute("PRAGMA table_info(peripherals)")
        columns = cursor.fetchall()
        column_names = [col[1] for col in columns]

        if 'specifications' in column_names and 'notes' in column_names:
            print("✅ Verification: Both columns exist in peripherals table")
        else:
            print("⚠️  Warning: Verification failed")

        return True

    except sqlite3.Error as e:
        print(f"❌ Error applying migration: {e}")
        conn.rollback()
        return False

    finally:
        conn.close()

if __name__ == "__main__":
    apply_migration()
