#!/usr/bin/env bash
# Mode-switch CLI — lets the agent change its own operating mode.
#
# Usage: mode <normal|spec|plan>
#
# Writes the requested mode to the running node's channel, then prints that
# mode's operating instructions so guidance enters context only on switching.
set -euo pipefail

mode="${1:-}"
case "$mode" in
	normal | spec | plan) ;;
	*)
		echo "usage: mode <normal|spec|plan>" >&2
		exit 1
		;;
esac

: "${CRTR_NODE_ID:?pi-mode-switch requires CRTR_NODE_ID}"
: "${CRTR_CONTEXT_DIR:?pi-mode-switch requires CRTR_CONTEXT_DIR}"
dir="$(dirname "$CRTR_CONTEXT_DIR")/mode"
mkdir -p "$dir"

# Signal the running extension. Atomic write via temp + rename so the watcher
# never reads a half-written file.
tmp="$(mktemp "$dir/request.XXXXXX")"
printf '{"mode":"%s","token":"%s","source":"cli"}\n' "$mode" "$(date +%s)-$$-${RANDOM:-0}" >"$tmp"
mv -f "$tmp" "$dir/request.json"

# Hand the new mode's operating instructions to the agent.
guidance="$dir/guidance/$mode.txt"
if [ -f "$guidance" ]; then
	cat "$guidance"
else
	echo "[$mode mode] requested. (No running mode-switch extension detected for this node, so detailed guidance is unavailable.)"
fi
