#!/bin/bash
# start-pideo-pane.sh — Launch the video agent pane in cmux
#
# This script:
#   1. Starts pideo-daemon.py in the background (processes forwarded videos)
#   2. Launches pi interactively 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="${PIDEO_DIR:-${HOME}/.pideo}"
DAEMON="${PIDIR}/pideo-daemon.py"
PIDFILE="/tmp/pideo-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 pideo daemon (RPC mode)..."
python3 "$DAEMON" &
DAEMON_PID=$!
echo "$DAEMON_PID" > "$PIDFILE"
echo "   PID: $DAEMON_PID"
echo ""

cat << "WELCOME"
╔══════════════════════════════════════════════╗
║   🎬 pideo — Video Agent (Gemini 2.0 Flash)
║                                              ║
║   This pane runs the video analysis model.   ║
║   The daemon processes videos forwarded from ║
║   the primary pane automatically.            ║
║                                              ║
║   You can also chat with me directly!        ║
║   Just send me a YouTube/TikTok link!        ║
╚══════════════════════════════════════════════╝

WELCOME

# Launch pi interactively — daemon will be killed on exit via trap
exec pi --model "${PIDEO_PANE_MODEL:-google/gemini-2.5-flash}"
