"""
Migration script to add deployment_type and deployed_with_unit_id fields to roster table.

deployment_type: tracks what type of device a modem is deployed with:
- "seismograph" - Modem is connected to a seismograph
- "slm" - Modem is connected to a sound level meter
- NULL/empty - Not assigned or unknown

deployed_with_unit_id: stores the ID of the seismograph/SLM this modem is deployed with
(reverse relationship of deployed_with_modem_id)

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

import sqlite3
import os

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


def migrate_database():
    """Add deployment_type and deployed_with_unit_id columns to roster 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 roster table exists
    cursor.execute("SELECT name FROM sqlite_master WHERE type='table' AND name='roster'")
    table_exists = cursor.fetchone()

    if not table_exists:
        print("Roster table does not exist yet - will be created when app runs")
        conn.close()
        return

    # Check existing columns
    cursor.execute("PRAGMA table_info(roster)")
    columns = [col[1] for col in cursor.fetchall()]

    try:
        # Add deployment_type if not exists
        if 'deployment_type' not in columns:
            print("Adding deployment_type column to roster table...")
            cursor.execute("ALTER TABLE roster ADD COLUMN deployment_type TEXT")
            print("  Added deployment_type column")

            cursor.execute("CREATE INDEX IF NOT EXISTS ix_roster_deployment_type ON roster(deployment_type)")
            print("  Created index on deployment_type")
        else:
            print("deployment_type column already exists")

        # Add deployed_with_unit_id if not exists
        if 'deployed_with_unit_id' not in columns:
            print("Adding deployed_with_unit_id column to roster table...")
            cursor.execute("ALTER TABLE roster ADD COLUMN deployed_with_unit_id TEXT")
            print("  Added deployed_with_unit_id column")

            cursor.execute("CREATE INDEX IF NOT EXISTS ix_roster_deployed_with_unit_id ON roster(deployed_with_unit_id)")
            print("  Created index on deployed_with_unit_id")
        else:
            print("deployed_with_unit_id column already exists")

        conn.commit()
        print("\nMigration completed successfully!")

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

    finally:
        conn.close()


if __name__ == "__main__":
    migrate_database()
