#!/usr/bin/env python3
"""
Apply migration 009: Add thumbnail_path field
"""
import sqlite3
from pathlib import Path

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

def apply_migration():
    """Apply migration 009"""
    print(f"Applying migration 009 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 009 applied successfully")
        print("   - Added thumbnail_path column")

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

        if 'thumbnail_path' in column_names:
            print("✅ Verification: thumbnail_path column exists in peripheral_photos 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()
