#!/usr/bin/env python3
"""
Apply SQL migration 006 to existing database
Migration 006: Add purchase metadata fields to devices table
"""

import os
import sqlite3

DB_PATH = os.path.join(os.path.dirname(__file__), "data", "data.db")
MIGRATION_PATH = os.path.join(
    os.path.dirname(__file__), "migrations", "006_add_purchase_fields.sql"
)

COLUMNS = ["purchase_store", "purchase_date", "purchase_price"]


def apply_migration():
    if not os.path.exists(DB_PATH):
        print(f"❌ Database not found at {DB_PATH}")
        print("   It will be created automatically on first backend start.")
        return

    if not os.path.exists(MIGRATION_PATH):
        print(f"❌ Migration file not found at {MIGRATION_PATH}")
        return

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

    try:
        cursor.execute("PRAGMA table_info(devices)")
        existing_columns = {row[1] for row in cursor.fetchall()}

        missing = [col for col in COLUMNS if col not in existing_columns]
        if not missing:
            print("⚠️  Migration 006 already applied (purchase columns exist)")
            return

        print("🔄 Applying migration 006 (purchase fields)...")
        with open(MIGRATION_PATH, "r", encoding="utf-8") as f:
            statements = [
                stmt.strip()
                for stmt in f.read().split(";")
                if stmt.strip()
            ]

        for stmt in statements:
            cursor.execute(stmt)

        conn.commit()
        print("✅ Migration 006 applied successfully.")
    except sqlite3.Error as exc:
        conn.rollback()
        print(f"❌ Error applying migration 006: {exc}")
    finally:
        conn.close()


if __name__ == "__main__":
    apply_migration()
