"""
Migration script to add unit history timeline support.

This creates the unit_history table to track all changes to units:
- Note changes (archived old notes, new notes)
- Deployment status changes (deployed/benched)
- Retired status changes
- Other field changes

Run this script once to migrate an existing database.
"""

import sqlite3
import os

# Database path
DB_PATH = "./data/seismo_fleet.db"

def migrate_database():
    """Create the unit_history table"""

    if not os.path.exists(DB_PATH):
        print(f"Database not found at {DB_PATH}")
        print("The database will be created automatically when you run the application.")
        return

    print(f"Migrating database: {DB_PATH}")

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

    # Check if unit_history table already exists
    cursor.execute("SELECT name FROM sqlite_master WHERE type='table' AND name='unit_history'")
    if cursor.fetchone():
        print("Migration already applied - unit_history table exists")
        conn.close()
        return

    print("Creating unit_history table...")

    try:
        cursor.execute("""
            CREATE TABLE unit_history (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                unit_id TEXT NOT NULL,
                change_type TEXT NOT NULL,
                field_name TEXT,
                old_value TEXT,
                new_value TEXT,
                changed_at TIMESTAMP NOT NULL,
                source TEXT DEFAULT 'manual',
                notes TEXT
            )
        """)
        print("  ✓ Created unit_history table")

        # Create indexes for better query performance
        cursor.execute("CREATE INDEX idx_unit_history_unit_id ON unit_history(unit_id)")
        print("  ✓ Created index on unit_id")

        cursor.execute("CREATE INDEX idx_unit_history_changed_at ON unit_history(changed_at)")
        print("  ✓ Created index on changed_at")

        conn.commit()
        print("\nMigration completed successfully!")
        print("Units will now track their complete history of changes.")

    except sqlite3.Error as e:
        print(f"\nError during migration: {e}")
        conn.rollback()
        raise

    finally:
        conn.close()


if __name__ == "__main__":
    migrate_database()
