"""
Migration: add `pending_deployments` table.

Stores "I just installed this seismograph" captures from the field.
A pending deployment is the prospective form of a UnitAssignment —
captured at install time (photo + coords + maybe a free-text note),
classified later (project + location chosen at a desk).

Once classified, a real UnitAssignment is created, the pending row's
status flips to "assigned", and resulting_assignment_id points at the
new assignment for audit.

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

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

import os
import sqlite3

DB_PATH = "./data/seismo_fleet.db"


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()

    cur.execute("""
        CREATE TABLE IF NOT EXISTS pending_deployments (
            id                       TEXT PRIMARY KEY,
            unit_id                  TEXT NOT NULL,
            captured_at              DATETIME NOT NULL,
            coordinates              TEXT,
            operator_note            TEXT,
            photo_filename           TEXT,
            status                   TEXT NOT NULL DEFAULT 'awaiting',
            promoted_at              DATETIME,
            resulting_assignment_id  TEXT,
            cancelled_at             DATETIME,
            cancelled_reason         TEXT,
            created_at               DATETIME NOT NULL DEFAULT (datetime('now')),
            updated_at               DATETIME NOT NULL DEFAULT (datetime('now'))
        )
    """)
    print("  Table 'pending_deployments' ready.")

    # Indexes — operators will query by status (hopper list) and by
    # unit_id (per-unit detail page → "is there a pending capture?").
    cur.execute("""
        CREATE INDEX IF NOT EXISTS idx_pending_deployments_status
            ON pending_deployments (status)
    """)
    cur.execute("""
        CREATE INDEX IF NOT EXISTS idx_pending_deployments_unit_id
            ON pending_deployments (unit_id)
    """)
    cur.execute("""
        CREATE INDEX IF NOT EXISTS idx_pending_deployments_captured_at
            ON pending_deployments (captured_at)
    """)
    print("  Indexes ready.")

    conn.commit()
    conn.close()


if __name__ == "__main__":
    print("Running migration: add pending_deployments table")
    migrate_database()
    print("Done.")
