"""
Migration script to add device type support to the roster table.

This adds columns for:
- device_type (seismograph/modem discriminator)
- Seismograph-specific fields (calibration dates, modem pairing)
- Modem-specific fields (IP address, phone number, hardware model)

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 new columns to the 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 device_type column already exists
    cursor.execute("PRAGMA table_info(roster)")
    columns = [col[1] for col in cursor.fetchall()]

    if "device_type" in columns:
        print("Migration already applied - device_type column exists")
        conn.close()
        return

    print("Adding new columns to roster table...")

    try:
        # Add device type discriminator
        cursor.execute("ALTER TABLE roster ADD COLUMN device_type TEXT DEFAULT 'seismograph'")
        print("  ✓ Added device_type column")

        # Add seismograph-specific fields
        cursor.execute("ALTER TABLE roster ADD COLUMN last_calibrated DATE")
        print("  ✓ Added last_calibrated column")

        cursor.execute("ALTER TABLE roster ADD COLUMN next_calibration_due DATE")
        print("  ✓ Added next_calibration_due column")

        cursor.execute("ALTER TABLE roster ADD COLUMN deployed_with_modem_id TEXT")
        print("  ✓ Added deployed_with_modem_id column")

        # Add modem-specific fields
        cursor.execute("ALTER TABLE roster ADD COLUMN ip_address TEXT")
        print("  ✓ Added ip_address column")

        cursor.execute("ALTER TABLE roster ADD COLUMN phone_number TEXT")
        print("  ✓ Added phone_number column")

        cursor.execute("ALTER TABLE roster ADD COLUMN hardware_model TEXT")
        print("  ✓ Added hardware_model column")

        # Set all existing units to seismograph type
        cursor.execute("UPDATE roster SET device_type = 'seismograph' WHERE device_type IS NULL")
        print("  ✓ Set existing units to seismograph type")

        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()
