#!/bin/bash
# start-pimage-pane.sh — Launch the vision agent pane in cmux
#
# This script:
#   1. Starts pimage-daemon.py in the background (processes forwarded images)
#   2. Launches pi interactively with mimo-v2.5 for direct use
#   3. Kills the daemon when pi exits
#
# Use as the "command" in a cmux surface, or run manually.

set -euo pipefail

PIDIR="${PIMAGE_DIR:-${HOME}/.pimage}"
DAEMON="${PIDIR}/pimage-daemon.py"
PIDFILE="/tmp/pimage-daemon.pid"

cleanup() {
  local daemon_pid
  if [[ -f "$PIDFILE" ]]; then
    daemon_pid=$(cat "$PIDFILE")
    kill "$daemon_pid" 2>/dev/null || true
    rm -f "$PIDFILE"
  fi
  exit 0
}
trap cleanup SIGINT SIGTERM EXIT

# Start Python daemon in background
echo "🧩 Starting pimage daemon (RPC mode)..."
python3 "$DAEMON" &
DAEMON_PID=$!
echo "$DAEMON_PID" > "$PIDFILE"
echo "   PID: $DAEMON_PID"
echo ""

cat << "WELCOME"
╔══════════════════════════════════════════════════╗
║   🧩 pimage — Vision Agent (mimo-v2.5)          ║
║                                                  ║
║   This pane runs the vision model.               ║
║   The daemon processes images forwarded from     ║
║   the primary pane automatically.                ║
║                                                  ║
║   You can also chat with me directly!            ║
╚══════════════════════════════════════════════════╝

WELCOME

# Launch pi interactively — daemon will be killed on exit via trap
exec pi --model "${PIMAGE_PANE_MODEL:-opencode-go/mimo-v2.5}"
