#!/usr/bin/env python3
"""
Migration script to add documentation fields to peripherals table.
Adds: description, synthese, cli columns
"""

import sqlite3
import os

DB_PATH = "backend/data/peripherals.db"

def migrate():
    """Add new columns to peripherals table"""

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

    conn = sqlite3.connect(DB_PATH)
    cursor = conn.cursor()

    try:
        # Check existing columns
        cursor.execute("PRAGMA table_info(peripherals)")
        existing_columns = [row[1] for row in cursor.fetchall()]
        print(f"✅ Found {len(existing_columns)} existing columns")

        columns_to_add = []

        # Check and add description
        if 'description' not in existing_columns:
            columns_to_add.append(('description', 'TEXT'))

        # Check and add synthese
        if 'synthese' not in existing_columns:
            columns_to_add.append(('synthese', 'TEXT'))

        # Check and add cli
        if 'cli' not in existing_columns:
            columns_to_add.append(('cli', 'TEXT'))

        if not columns_to_add:
            print("✅ All columns already exist. No migration needed.")
            return True

        # Add missing columns
        for col_name, col_type in columns_to_add:
            sql = f"ALTER TABLE peripherals ADD COLUMN {col_name} {col_type}"
            print(f"🔧 Adding column: {col_name} {col_type}")
            cursor.execute(sql)

        conn.commit()
        print(f"✅ Migration completed successfully! Added {len(columns_to_add)} columns.")

        # Verify
        cursor.execute("PRAGMA table_info(peripherals)")
        new_columns = [row[1] for row in cursor.fetchall()]
        print(f"✅ Total columns now: {len(new_columns)}")

        return True

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

    finally:
        conn.close()

if __name__ == "__main__":
    print("=" * 60)
    print("MIGRATION: Add documentation fields to peripherals")
    print("=" * 60)
    migrate()
