#!/usr/bin/env bash
# Restore ~/.mugi/chats_db.json after the 2026-05-06 test-wipe incident.
#
# What happened: a test in test_mugi_backend_conversation_routes.py wrote a
# 1-entry stub to the user's real ~/.mugi/chats_db.json (the test fixture's
# fake delegate was missing tab_id / title; the routes saved it verbatim).
# The next backend launch ran ``repair_conversation_meta_from_message_threads``
# which re-stubbed every orphaned thread as "Untitled" because chats_db.json
# no longer carried real titles.
#
# What this script does, in order:
#   1. Quits Mugi.app gracefully (so the running backend's drain hook fires
#      and writes its current state — but to a tmp PRESERVE file, not the
#      live chats_db.json — see step 3).
#   2. Snapshots the current (corrupted) chats_db.json into the backup dir
#      under a ``PRESERVE.20260506.user_request`` suffix so the user can
#      always inspect it.
#   3. Picks the newest backup whose tab[0] has the full ``tab_id`` + ``title``
#      keys (the tell-tale stripped-keys backups are the ones the test wrote).
#   4. Copies that backup over chats_db.json.
#   5. Tells the user to relaunch Mugi.

set -euo pipefail

MUGI_DIR="${HOME}/.mugi"
BDIR="${MUGI_DIR}/backups/chats_db"
LIVE="${MUGI_DIR}/chats_db.json"

if [[ ! -d "${BDIR}" ]]; then
  echo "ERROR: no backup dir at ${BDIR}" >&2
  exit 1
fi

echo "[1/5] Asking Mugi.app to quit gracefully..."
osascript -e 'tell application "Mugi" to quit' 2>/dev/null || true
# Wait up to 10s for the backend's drain hook to finish.
for i in {1..20}; do
  if ! pgrep -f 'mugi_backend' >/dev/null 2>&1; then
    echo "    backend exited"
    break
  fi
  sleep 0.5
done

echo "[2/5] Preserving the corrupted live file as a snapshot..."
TS=$(date -u +"%Y%m%dT%H%M%SZ")
PRESERVE="${BDIR}/chats_db.json.PRESERVE.${TS}"
if [[ -f "${LIVE}" ]]; then
  cp -p "${LIVE}" "${PRESERVE}"
  echo "    snapshot at ${PRESERVE}"
fi

echo "[3/5] Finding the newest pre-wipe backup (tab[0] has tab_id + title)..."
BEST=$(/usr/bin/python3 - "${BDIR}" <<'PY'
import json, os, sys, glob
bdir = sys.argv[1]
candidates = sorted(glob.glob(os.path.join(bdir, "*Z")), key=os.path.getmtime, reverse=True)
for p in candidates:
    if "PANIC" in p or "PRESERVE" in p:
        continue
    try:
        with open(p) as f:
            d = json.load(f)
    except Exception:
        continue
    tabs = d.get("tabs") or []
    if not tabs:
        continue
    if "tab_id" in tabs[0] and "title" in tabs[0]:
        print(p)
        break
PY
)

if [[ -z "${BEST}" ]]; then
  echo "ERROR: no pre-wipe backup found in ${BDIR}" >&2
  exit 2
fi
echo "    chose: ${BEST}"

echo "[4/5] Restoring chats_db.json..."
cp -p "${BEST}" "${LIVE}"

echo "[5/5] Done."
echo
echo "Now relaunch Mugi. Your conversations will reappear with their original titles."
echo "If the relaunch creates a couple of new 'Untitled' rows for chats that arrived"
echo "after the chosen backup, you can just trash them — the underlying messages are"
echo "intact in chats.db (SQLite)."
