#!/usr/bin/env python3
"""
Apply migration 007: Add cli_yaml and cli_raw fields
"""
import sqlite3
from pathlib import Path

# Database paths
PERIPHERALS_DB = Path(__file__).parent / "data" / "peripherals.db"
MIGRATION_FILE = Path(__file__).parent / "migrations" / "007_add_cli_split_fields.sql"

def apply_migration():
    """Apply the migration"""
    if not PERIPHERALS_DB.exists():
        print(f"Error: Database not found at {PERIPHERALS_DB}")
        return False

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

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

    # Apply migration
    conn = sqlite3.connect(str(PERIPHERALS_DB))
    try:
        # Check if columns already exist
        cursor = conn.cursor()
        cursor.execute("PRAGMA table_info(peripherals)")
        columns = [row[1] for row in cursor.fetchall()]

        if 'cli_yaml' in columns and 'cli_raw' in columns:
            print("✓ Migration already applied (cli_yaml and cli_raw columns exist)")
            return True

        # Execute migration
        cursor.executescript(migration_sql)
        conn.commit()
        print("✓ Migration 007 applied successfully")
        print("  - Added cli_yaml column")
        print("  - Added cli_raw column")
        print("  - Migrated existing cli data to cli_raw")
        return True

    except Exception as e:
        print(f"✗ Migration failed: {e}")
        conn.rollback()
        return False
    finally:
        conn.close()

if __name__ == "__main__":
    apply_migration()
