#!/bin/sh
set -eu

# Pretty colors (only if stdout is tty and supports colors)
if [ -t 1 ] && [ -n "${TERM:-}" ] && [ "$TERM" != "dumb" ]; then
  BOLD="$(printf '\033[1m')"
  GREEN="$(printf '\033[32m')"
  RED="$(printf '\033[31m')"
  YELLOW="$(printf '\033[33m')"
  RESET="$(printf '\033[0m')"
else
  BOLD=""; GREEN=""; RED=""; YELLOW=""; RESET=""
fi

info()  { printf "%s==>%s %s\n" "$GREEN" "$RESET" "$1"; }
warn()  { printf "%s!!%s  %s\n" "$YELLOW" "$RESET" "$1"; }
error() { printf "%sERROR%s %s\n" "$RED" "$RESET" "$1" >&2; }
die()   { error "$1"; exit 1; }

# 1. Check docker
command -v docker >/dev/null 2>&1 || die "Docker not found. Install: https://docs.docker.com/engine/install/"

# 2. Check docker compose v2 (plugin) is available
docker compose version >/dev/null 2>&1 || die "Docker Compose v2 not found. Update Docker to a recent version."

# 3. Check daemon is running
docker info >/dev/null 2>&1 || die "Docker daemon is not running. Start Docker first."

# 4. Setup directory
YOJIMBO_HOME="${YOJIMBO_HOME:-$HOME/.yojimbo}"
mkdir -p "$YOJIMBO_HOME"
info "Install dir: $YOJIMBO_HOME"

# 5. Download docker-compose.yml (always overwrite to keep in sync with current release)
info "Downloading docker-compose.yml..."
curl -fsSL https://yojimbo.dev/docker-compose.yml -o "$YOJIMBO_HOME/docker-compose.yml" \
  || die "Failed to download docker-compose.yml"

# 6. AGENT_LOCAL_TOKEN: token is now baked into the public image and pinned to
# 127.0.0.1 in compose. No per-install random token (the frontend SDK reads
# NEXT_PUBLIC_API_KEY from the baked bundle, can't be runtime-injected). If
# you have an old .env from a previous install with random AGENT_LOCAL_TOKEN,
# remove it so compose interpolation doesn't override the static value:
ENV_FILE="$YOJIMBO_HOME/.env"
if [ -f "$ENV_FILE" ] && grep -q '^AGENT_LOCAL_TOKEN=' "$ENV_FILE"; then
  warn "Found stale random token in $ENV_FILE — removing (token is now baked into image)."
  rm -f "$ENV_FILE"
fi

# 7. Pull images
info "Pulling images..."
(cd "$YOJIMBO_HOME" && docker compose pull) || die "Failed to pull images"

# 8. Start
info "Starting containers..."
(cd "$YOJIMBO_HOME" && docker compose up -d) || die "Failed to start containers"

# 9. Install helper CLI in ~/.local/bin (no sudo)
BIN_DIR="$HOME/.local/bin"
mkdir -p "$BIN_DIR"
HELPER="$BIN_DIR/yojimbo"

cat > "$HELPER" <<'HELPER_EOF'
#!/bin/sh
# Yojimbo CLI — manage docker installation
set -eu

YOJIMBO_HOME="${YOJIMBO_HOME:-$HOME/.yojimbo}"
COMPOSE_FILE="$YOJIMBO_HOME/docker-compose.yml"

if [ ! -f "$COMPOSE_FILE" ]; then
  echo "Yojimbo not installed. Run: curl -fsSL https://yojimbo.dev/install.sh | sh" >&2
  exit 1
fi

case "${1:-}" in
  start)
    cd "$YOJIMBO_HOME" && docker compose up -d
    ;;
  stop)
    cd "$YOJIMBO_HOME" && docker compose down
    ;;
  restart)
    cd "$YOJIMBO_HOME" && docker compose restart
    ;;
  status)
    cd "$YOJIMBO_HOME" && docker compose ps
    ;;
  logs)
    cd "$YOJIMBO_HOME" && docker compose logs -f --tail=100 "${2:-}"
    ;;
  update)
    echo "Refreshing docker-compose.yml..."
    curl -fsSL https://yojimbo.dev/docker-compose.yml -o "$YOJIMBO_HOME/docker-compose.yml" \
      || { echo "Failed to download docker-compose.yml"; exit 1; }
    echo "Pulling latest images..."
    cd "$YOJIMBO_HOME" && docker compose pull && docker compose up -d
    echo "Updated. Open http://localhost:3000"
    ;;
  uninstall)
    cd "$YOJIMBO_HOME" && docker compose down -v
    rm -rf "$YOJIMBO_HOME"
    rm -f "$HOME/.local/bin/yojimbo"
    echo "Yojimbo uninstalled."
    ;;
  open)
    URL="http://localhost:3000"
    if command -v xdg-open >/dev/null 2>&1; then xdg-open "$URL"
    elif command -v open >/dev/null 2>&1; then open "$URL"
    elif command -v wslview >/dev/null 2>&1; then wslview "$URL"
    else echo "Open $URL in your browser"
    fi
    ;;
  *)
    cat <<USAGE
Usage: yojimbo <command>

Commands:
  start       Start containers (after stop or reboot)
  stop        Stop containers
  restart     Restart containers
  status      Show container status
  logs [svc]  Tail logs (optionally for one service: agent|frontend)
  update      Pull latest images and restart
  open        Open http://localhost:3000 in browser
  uninstall   Stop containers and remove ~/.yojimbo
USAGE
    exit 1
    ;;
esac
HELPER_EOF

chmod +x "$HELPER"
info "Installed CLI: $HELPER"

# 10. PATH check
case ":$PATH:" in
  *":$BIN_DIR:"*)
    PATH_OK=1
    ;;
  *)
    PATH_OK=0
    ;;
esac

# 11. Final summary
echo ""
info "${BOLD}Yojimbo is starting up.${RESET}"
echo ""
echo "  Open: http://localhost:3000"
echo ""
if [ "$PATH_OK" = "1" ]; then
  echo "  Manage: yojimbo {start|stop|restart|status|logs|update|open|uninstall}"
else
  warn "$BIN_DIR is not in your PATH. Either:"
  warn "  - Run \`$HELPER ...\` directly, or"
  warn "  - Add to your shell rc:"
  warn "      echo 'export PATH=\"\$HOME/.local/bin:\$PATH\"' >> ~/.zshrc"
  warn "      echo 'export PATH=\"\$HOME/.local/bin:\$PATH\"' >> ~/.bashrc"
  warn "    then \`source ~/.zshrc\` (or open a new terminal)."
fi
echo ""
echo "  Containers will auto-start on system reboot (restart: unless-stopped policy)."
echo ""
