#!/bin/zsh
set -euo pipefail

# Usage:
#   scripts/thread_checkpoint.sh switch <from_thread> <to_thread> <reason>
#   scripts/thread_checkpoint.sh set-active <thread_id> <thread_title> <status> <last_user_intent>

WORKDIR="/Users/openclaw/.openclaw/workspace"
MEMDIR="$WORKDIR/memory"
ACTIVE_FILE="$MEMDIR/active-thread.md"
TODAY_FILE="$MEMDIR/$(date +%F).md"

mkdir -p "$MEMDIR"

timestamp_hm="$(date +%H:%M)"
timestamp_iso="$(date -u +%Y-%m-%dT%H:%M:%SZ)"

cmd="${1:-}"

case "$cmd" in
  switch)
    from_thread="${2:-}"
    to_thread="${3:-}"
    reason="${4:-user}"
    if [[ -z "$from_thread" || -z "$to_thread" ]]; then
      echo "Usage: $0 switch <from_thread> <to_thread> <reason>" >&2
      exit 1
    fi
    echo "- [${timestamp_hm}] THREAD_SWITCH from=${from_thread} to=${to_thread} reason=${reason}" >> "$TODAY_FILE"
    echo "Appended switch checkpoint to $TODAY_FILE"
    ;;

  set-active)
    thread_id="${2:-}"
    thread_title="${3:-}"
    thread_status="${4:-active}"
    last_user_intent="${5:-}"
    if [[ -z "$thread_id" || -z "$thread_title" ]]; then
      echo "Usage: $0 set-active <thread_id> <thread_title> <status> <last_user_intent>" >&2
      exit 1
    fi
    cat > "$ACTIVE_FILE" <<EOT
thread_id: ${thread_id}
thread_title: ${thread_title}
status: ${thread_status}
updated_at: ${timestamp_iso}
last_user_intent: "${last_user_intent}"
EOT
    echo "Updated $ACTIVE_FILE"
    ;;

  *)
    echo "Usage:" >&2
    echo "  $0 switch <from_thread> <to_thread> <reason>" >&2
    echo "  $0 set-active <thread_id> <thread_title> <status> <last_user_intent>" >&2
    exit 1
    ;;
esac
