#!/usr/bin/env python3
"""
Database migration: Add sound level meter fields to roster table.

Adds columns for sound_level_meter device type support.
"""

import sqlite3
from pathlib import Path

def migrate():
    """Add SLM fields to roster table if they don't exist."""

    # Try multiple possible database locations
    possible_paths = [
        Path("data/seismo_fleet.db"),
        Path("data/sfm.db"),
        Path("data/seismo.db"),
    ]

    db_path = None
    for path in possible_paths:
        if path.exists():
            db_path = path
            break

    if db_path is None:
        print(f"Database not found in any of: {[str(p) for p in possible_paths]}")
        print("Creating database with models.py will include new fields automatically.")
        return

    print(f"Using database: {db_path}")

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

    # Check if columns already exist
    cursor.execute("PRAGMA table_info(roster)")
    existing_columns = {row[1] for row in cursor.fetchall()}

    new_columns = {
        "slm_host": "TEXT",
        "slm_tcp_port": "INTEGER",
        "slm_model": "TEXT",
        "slm_serial_number": "TEXT",
        "slm_frequency_weighting": "TEXT",
        "slm_time_weighting": "TEXT",
        "slm_measurement_range": "TEXT",
        "slm_last_check": "DATETIME",
    }

    migrations_applied = []

    for column_name, column_type in new_columns.items():
        if column_name not in existing_columns:
            try:
                cursor.execute(f"ALTER TABLE roster ADD COLUMN {column_name} {column_type}")
                migrations_applied.append(column_name)
                print(f"✓ Added column: {column_name} ({column_type})")
            except sqlite3.OperationalError as e:
                print(f"✗ Failed to add column {column_name}: {e}")
        else:
            print(f"○ Column already exists: {column_name}")

    conn.commit()
    conn.close()

    if migrations_applied:
        print(f"\n✓ Migration complete! Added {len(migrations_applied)} new columns.")
    else:
        print("\n○ No migration needed - all columns already exist.")

    print("\nSound level meter fields are now available in the roster table.")
    print("Note: Use device_type='slm' for Sound Level Meters. Legacy 'sound_level_meter' has been deprecated.")


if __name__ == "__main__":
    migrate()
