#!/usr/bin/env bash
set -euo pipefail

IMAGE="${CANVAS_IMAGE:-ghcr.io/openhands/agent-canvas:latest}"
PORT="${PORT:-8000}"
NAME="agent-canvas-class-demo"
SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)"
STATE_DIR="$SCRIPT_DIR/state"
WORKSPACE_DIR="$SCRIPT_DIR/workspace"

fail() { printf '\nERROR: %s\n' "$*" >&2; exit 1; }

case "${1:-start}" in
  stop)
    docker stop "$NAME" >/dev/null 2>&1 && echo "Agent Canvas stopped." || echo "Agent Canvas is not running."
    exit 0 ;;
  logs)
    exec docker logs -f "$NAME" ;;
  status)
    docker ps -a --filter "name=^/${NAME}$" --format 'table {{.Names}}\t{{.Status}}\t{{.Ports}}'
    exit 0 ;;
  start) ;;
  *) fail "Usage: ./run.sh [start|stop|logs|status]" ;;
esac

command -v docker >/dev/null 2>&1 || fail "Docker is not installed. See https://docs.docker.com/engine/install/"
docker info >/dev/null 2>&1 || fail "Docker is installed but unavailable. Start it with 'sudo systemctl start docker', or fix Docker group permissions."

mkdir -p "$STATE_DIR" "$WORKSPACE_DIR"

# The official image runs as uid/gid 10001. These bind mounts are created by
# the host user, so make only the two demo directories writable by that user.
# Without this, the frontend starts but agent-server exits with EACCES and the
# browser reports a misleading 502 for 127.0.0.1:18000.
chmod a+rwx "$STATE_DIR" "$WORKSPACE_DIR"

if docker ps --format '{{.Names}}' | grep -Fxq "$NAME"; then
  echo "Agent Canvas is already running at http://localhost:$PORT/canvas"
  exit 0
fi
docker rm -f "$NAME" >/dev/null 2>&1 || true

echo "==> Starting official Agent Canvas image: $IMAGE"
echo "==> Mounted workspace: $WORKSPACE_DIR -> /projects/agent-canvas-demo"
docker run -d --rm --pull=missing \
  --name "$NAME" \
  -p "$PORT:8000" \
  -v "$STATE_DIR:/home/openhands/.openhands" \
  -v "$WORKSPACE_DIR:/projects/agent-canvas-demo" \
  "$IMAGE" >/dev/null

probe() {
  # Check the proxied backend, not merely the static Canvas page.
  if command -v curl >/dev/null 2>&1; then curl -fsS "http://localhost:$PORT/alive" >/dev/null 2>&1
  elif command -v wget >/dev/null 2>&1; then wget -qO- "http://localhost:$PORT/alive" >/dev/null 2>&1
  else return 2
  fi
}

printf '==> Waiting for Agent Canvas '
ready=0
for _ in $(seq 1 120); do
  set +e; probe; rc=$?; set -e
  if [ "$rc" -eq 0 ]; then ready=1; break; fi
  if [ "$rc" -eq 2 ]; then sleep 15; ready=1; break; fi
  printf '.'; sleep 2
done
printf '\n'

if [ "$ready" -ne 1 ]; then
  docker logs --tail 80 "$NAME" >&2 || true
  fail "Canvas did not answer within four minutes. Run: ./run.sh logs"
fi

URL="http://localhost:$PORT/canvas"
echo "==> Agent Canvas is ready: $URL"
command -v xdg-open >/dev/null 2>&1 && xdg-open "$URL" >/dev/null 2>&1 || true
printf '\nSelect workspace: /projects/agent-canvas-demo\nStop: ./run.sh stop    Logs: ./run.sh logs\n'
