"""
Migration: add `sort_order` column to `monitoring_locations` and seed
existing rows.

Lets operators reorder location cards via drag-and-drop on the project
detail page.  Lower sort_order renders first; ties fall back to name.

Seed strategy: for each existing project, assign sort_order = 0, 1, 2, …
to its locations in their current alphabetical-by-name order.  After
this migration, the visible card order on every existing project will
be unchanged.

Idempotent — safe to re-run.  Non-destructive — adds only.

Run with:
  docker exec terra-view-terra-view-1 python3 /app/backend/migrate_add_location_sort_order.py
"""

import os
import sqlite3

DB_PATH = "./data/seismo_fleet.db"


def _has_column(cur: sqlite3.Cursor, table: str, column: str) -> bool:
    cur.execute(f"PRAGMA table_info({table})")
    return any(row[1] == column for row in cur.fetchall())


def migrate_database() -> None:
    if not os.path.exists(DB_PATH):
        print(f"Database not found at {DB_PATH}")
        return

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

    added_column = False
    if not _has_column(cur, "monitoring_locations", "sort_order"):
        cur.execute("ALTER TABLE monitoring_locations ADD COLUMN sort_order INTEGER DEFAULT 0")
        added_column = True
        print("  Added column: monitoring_locations.sort_order")

    # Seed: for each project, set sort_order to its alphabetical index.
    # Re-runs are harmless — operator-edited orderings can be re-seeded by
    # passing FORCE_RESEED=1, but the default behavior leaves existing
    # nonzero sort_order values alone so we don't clobber user choices.
    force_reseed = os.environ.get("FORCE_RESEED") == "1"
    if added_column or force_reseed:
        cur.execute("SELECT DISTINCT project_id FROM monitoring_locations")
        projects = [r[0] for r in cur.fetchall()]
        seeded = 0
        for project_id in projects:
            cur.execute(
                "SELECT id FROM monitoring_locations WHERE project_id = ? ORDER BY name",
                (project_id,),
            )
            for idx, (loc_id,) in enumerate(cur.fetchall()):
                cur.execute(
                    "UPDATE monitoring_locations SET sort_order = ? WHERE id = ?",
                    (idx, loc_id),
                )
                seeded += 1
        print(f"  Seeded sort_order for {seeded} location(s) across {len(projects)} project(s).")
    else:
        print("  monitoring_locations.sort_order already present — leaving existing values alone.")
        print("  (Set FORCE_RESEED=1 to re-seed by alphabetical order.)")

    conn.commit()
    conn.close()


if __name__ == "__main__":
    print("Running migration: add sort_order to monitoring_locations")
    migrate_database()
    print("Done.")
