"""
Migration: Add one-off schedule fields to recurring_schedules table

Adds start_datetime and end_datetime columns for one-off recording schedules.

Run this script once to update existing databases:
    python -m backend.migrate_add_oneoff_schedule_fields
"""

import sqlite3
import os

DB_PATH = "data/seismo_fleet.db"


def migrate():
    """Add one-off schedule columns to recurring_schedules table."""
    if not os.path.exists(DB_PATH):
        print(f"Database not found at {DB_PATH}")
        return False

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

    try:
        cursor.execute("""
            SELECT name FROM sqlite_master
            WHERE type='table' AND name='recurring_schedules'
        """)
        if not cursor.fetchone():
            print("recurring_schedules table does not exist yet. Will be created on app startup.")
            conn.close()
            return True

        cursor.execute("PRAGMA table_info(recurring_schedules)")
        columns = [row[1] for row in cursor.fetchall()]

        added = False

        if "start_datetime" not in columns:
            print("Adding start_datetime column to recurring_schedules table...")
            cursor.execute("""
                ALTER TABLE recurring_schedules
                ADD COLUMN start_datetime DATETIME NULL
            """)
            added = True

        if "end_datetime" not in columns:
            print("Adding end_datetime column to recurring_schedules table...")
            cursor.execute("""
                ALTER TABLE recurring_schedules
                ADD COLUMN end_datetime DATETIME NULL
            """)
            added = True

        if added:
            conn.commit()
            print("Successfully added one-off schedule columns.")
        else:
            print("One-off schedule columns already exist.")

        conn.close()
        return True

    except Exception as e:
        print(f"Migration failed: {e}")
        conn.close()
        return False


if __name__ == "__main__":
    success = migrate()
    exit(0 if success else 1)
