"""
Migration: Rename recording_sessions table to monitoring_sessions

Renames the table and updates the model name from RecordingSession to MonitoringSession.
Run once per database: python backend/migrate_rename_recording_to_monitoring_sessions.py
"""

import sqlite3
import sys
from pathlib import Path


def migrate(db_path: str):
    """Run the migration."""
    print(f"Migrating database: {db_path}")

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

    try:
        cursor.execute("SELECT name FROM sqlite_master WHERE type='table' AND name='recording_sessions'")
        if not cursor.fetchone():
            cursor.execute("SELECT name FROM sqlite_master WHERE type='table' AND name='monitoring_sessions'")
            if cursor.fetchone():
                print("monitoring_sessions table already exists. Skipping migration.")
            else:
                print("recording_sessions table does not exist. Skipping migration.")
            return

        print("Renaming recording_sessions -> monitoring_sessions...")
        cursor.execute("ALTER TABLE recording_sessions RENAME TO monitoring_sessions")

        conn.commit()
        print("Migration completed successfully!")

    except Exception as e:
        print(f"Migration failed: {e}")
        conn.rollback()
        raise
    finally:
        conn.close()


if __name__ == "__main__":
    db_path = "./data/seismo_fleet.db"

    if len(sys.argv) > 1:
        db_path = sys.argv[1]

    if not Path(db_path).exists():
        print(f"Database not found: {db_path}")
        sys.exit(1)

    migrate(db_path)
