"""
Database Migration: Add out_for_calibration field to roster table

Changes:
- Adds out_for_calibration BOOLEAN column (default FALSE) to roster table
- Safe to run multiple times (idempotent)
- No data loss

Usage:
    python backend/migrate_add_out_for_calibration.py
"""

import sys
import os

sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from sqlalchemy import create_engine, text
from sqlalchemy.orm import sessionmaker

SQLALCHEMY_DATABASE_URL = "sqlite:///./data/seismo_fleet.db"
engine = create_engine(SQLALCHEMY_DATABASE_URL, connect_args={"check_same_thread": False})
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)


def migrate():
    db = SessionLocal()
    try:
        print("=" * 60)
        print("Migration: Add out_for_calibration to roster")
        print("=" * 60)

        # Check if column already exists
        result = db.execute(text("PRAGMA table_info(roster)")).fetchall()
        columns = [row[1] for row in result]

        if "out_for_calibration" in columns:
            print("Column out_for_calibration already exists. Skipping.")
        else:
            db.execute(text("ALTER TABLE roster ADD COLUMN out_for_calibration BOOLEAN DEFAULT FALSE"))
            db.commit()
            print("Added out_for_calibration column to roster table.")

        print("Migration complete.")
    except Exception as e:
        db.rollback()
        print(f"Error: {e}")
        raise
    finally:
        db.close()


if __name__ == "__main__":
    migrate()
