#!/bin/bash
# install.sh — Live Status v4 installer
#
# Installs npm dependencies and deploys the gateway:startup hook.
# The watcher daemon starts automatically on next gateway restart.
#
# Usage: bash install.sh [--workspace DIR]

set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
WORKSPACE="${1:-/home/node/.openclaw/workspace}"

# Parse flags
while [[ "$#" -gt 0 ]]; do
  case "$1" in
    --workspace) WORKSPACE="$2"; shift 2 ;;
    *) shift ;;
  esac
done

echo "==================================="
echo "  Live Status v4 Installer"
echo "==================================="
echo "Project: $SCRIPT_DIR"
echo "Workspace: $WORKSPACE"
echo ""

# 1. Install npm dependencies
echo "[1/3] Installing npm dependencies..."
cd "$SCRIPT_DIR"
npm install --production
echo "      Done."

# 2. Deploy hook
echo "[2/3] Deploying gateway:startup hook..."
HOOKS_DIR="$WORKSPACE/hooks"
mkdir -p "$HOOKS_DIR/status-watcher-hook"
cp -r "$SCRIPT_DIR/hooks/status-watcher-hook/." "$HOOKS_DIR/status-watcher-hook/"
echo "      Hook deployed to: $HOOKS_DIR/status-watcher-hook/"

# 3. Print required environment variables
echo "[3/3] Post-install configuration"
echo ""
echo "==================================="
echo "  Required Environment Variables"
echo "==================================="
echo ""
echo "Set these before the watcher will function:"
echo ""
echo "  MM_TOKEN         Mattermost bot token"
echo "                   (find in openclaw.json -> mattermost.accounts)"
echo ""
echo "  MM_URL           Mattermost base URL"
echo "                   e.g. https://slack.solio.tech"
echo ""
echo "  TRANSCRIPT_DIR   Path to agent sessions directory"
echo "                   e.g. /home/node/.openclaw/agents/main/sessions"
echo ""
echo "  SESSIONS_JSON    Path to sessions.json"
echo "                   e.g. /home/node/.openclaw/agents/main/sessions/sessions.json"
echo ""
echo "Optional (shown with defaults):"
echo "  THROTTLE_MS=500               Update interval (ms)"
echo "  IDLE_TIMEOUT_S=60             Idle before marking session done"
echo "  MAX_STATUS_LINES=15           Lines shown in status box"
echo "  MAX_ACTIVE_SESSIONS=20        Concurrent session limit"
echo "  HEALTH_PORT=9090              Health endpoint port (0=disabled)"
echo "  LOG_LEVEL=info                Logging level"
echo "  PID_FILE=/tmp/status-watcher.pid"
echo ""
echo "==================================="
echo "  Installation Complete"
echo "==================================="
echo ""
echo "The watcher starts automatically on next gateway startup."
echo "To start immediately (with env vars set):"
echo "  node $SCRIPT_DIR/src/watcher-manager.js start"
echo ""
echo "Health check (once running):"
echo "  curl http://localhost:9090/health"
