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

INSTALL_DIR="${ZOI_AGENT_DIR:-$HOME/zoi-agent}"
SOURCE_URL="${ZOI_AGENT_SOURCE_URL:-https://ponsagent.com/zoi-agent-source.zip}"

for command_name in curl unzip docker; do
  if ! command -v "$command_name" >/dev/null 2>&1; then
    printf 'Missing required command: %s\n' "$command_name" >&2
    printf 'Install Docker and unzip, then run this script again.\n' >&2
    exit 1
  fi
done

mkdir -p "$INSTALL_DIR"
archive="$(mktemp)"
trap 'rm -f "$archive"' EXIT
curl --fail --location --silent --show-error "$SOURCE_URL" --output "$archive"
unzip -q -o "$archive" -d "$INSTALL_DIR"
cd "$INSTALL_DIR"

if [ ! -f apps/agent/.env ]; then
  cp apps/agent/.env.example apps/agent/.env
fi

docker network inspect pons-control >/dev/null 2>&1 || docker network create pons-control >/dev/null

printf '\nZoi Agent source installed at %s\n' "$INSTALL_DIR"
printf '1. Edit %s/apps/agent/.env and add your own RPC, API keys, and wallet.\n' "$INSTALL_DIR"
printf '2. Keep AGENT_MODE=observe until doctor passes.\n'
printf '3. Start the service with:\n'
printf '   cd %s && docker compose -f docker-compose.agent.yml up -d --build\n' "$INSTALL_DIR"
