#!/usr/bin/env python3
"""
Migration: Add data_collection_mode column to projects table.

Values:
  "remote"  — units have modems; data pulled via FTP/scheduler automatically
  "manual"  — no modem; SD cards retrieved daily and uploaded by hand

All existing projects are backfilled to "manual" (safe conservative default).

Run once inside the Docker container:
    docker exec terra-view python3 backend/migrate_add_project_data_collection_mode.py
"""
from pathlib import Path

DB_PATH = Path("data/seismo_fleet.db")


def migrate():
    import sqlite3

    if not DB_PATH.exists():
        print(f"Database not found at {DB_PATH}. Are you running from /home/serversdown/terra-view?")
        return

    conn = sqlite3.connect(DB_PATH)
    conn.row_factory = sqlite3.Row
    cur = conn.cursor()

    # ── 1. Add column (idempotent) ───────────────────────────────────────────
    cur.execute("PRAGMA table_info(projects)")
    existing_cols = {row["name"] for row in cur.fetchall()}

    if "data_collection_mode" not in existing_cols:
        cur.execute("ALTER TABLE projects ADD COLUMN data_collection_mode TEXT DEFAULT 'manual'")
        conn.commit()
        print("✓ Added column data_collection_mode to projects")
    else:
        print("○ Column data_collection_mode already exists — skipping ALTER TABLE")

    # ── 2. Backfill NULLs to 'manual' ────────────────────────────────────────
    cur.execute("UPDATE projects SET data_collection_mode = 'manual' WHERE data_collection_mode IS NULL")
    updated = cur.rowcount
    conn.commit()
    conn.close()

    if updated:
        print(f"✓ Backfilled {updated} project(s) to data_collection_mode='manual'.")
    print("Migration complete.")


if __name__ == "__main__":
    migrate()
