#!/bin/sh
set -eu

base_url=${SANDBOX_INSTALL_BASE_URL:-https://sandbox.0-uk.com/downloads}
wheel_name="sandbox_control_client-0.1.0-py3-none-any.whl"
expected_sha256="f7b704f184d5cab9bebac1cb382cacfe6f3b26d0fd4df77784d24b004aad5fdc"
python_bin=${PYTHON:-}

if [ -z "$python_bin" ]; then
  python_bin=$(command -v python3 || true)
fi
if [ -z "$python_bin" ]; then
  printf '%s\n' "Sandbox requires Python 3.12 or newer." >&2
  exit 1
fi

temporary_dir=$(mktemp -d "${TMPDIR:-/tmp}/sandbox-client.XXXXXX")
cleanup() {
  rm -rf -- "$temporary_dir"
}
trap cleanup EXIT HUP INT TERM
wheel_path="$temporary_dir/$wheel_name"

if command -v curl >/dev/null 2>&1; then
  curl --fail --silent --show-error --location \
    "$base_url/$wheel_name" --output "$wheel_path"
else
  "$python_bin" -c \
    'import sys, urllib.request; urllib.request.urlretrieve(sys.argv[1], sys.argv[2])' \
    "$base_url/$wheel_name" "$wheel_path"
fi

actual_sha256=$($python_bin -c \
  'import hashlib, pathlib, sys; print(hashlib.sha256(pathlib.Path(sys.argv[1]).read_bytes()).hexdigest())' \
  "$wheel_path")
if [ "$actual_sha256" != "$expected_sha256" ]; then
  printf '%s\n' "Sandbox client checksum verification failed." >&2
  exit 1
fi

if command -v uv >/dev/null 2>&1; then
  uv tool install --force "$wheel_path"
else
  python_version=$($python_bin -c 'import sys; print(f"{sys.version_info.major}.{sys.version_info.minor}")')
  if ! $python_bin -c 'import sys; raise SystemExit(sys.version_info < (3, 12))'; then
    printf 'Sandbox requires Python 3.12 or newer; found %s.\n' "$python_version" >&2
    exit 1
  fi
  install_root=${SANDBOX_INSTALL_ROOT:-"$HOME/.local/share/sandbox-client"}
  bin_root=${SANDBOX_BIN_DIR:-"$HOME/.local/bin"}
  "$python_bin" -m venv "$install_root"
  "$install_root/bin/python" -m pip install --disable-pip-version-check --upgrade "$wheel_path"
  mkdir -p "$bin_root"
  ln -sfn "$install_root/bin/sandbox" "$bin_root/sandbox"
  ln -sfn "$install_root/bin/sandbox-mcp" "$bin_root/sandbox-mcp"
  printf 'Installed sandbox and sandbox-mcp in %s.\n' "$bin_root"
  case ":$PATH:" in
    *":$bin_root:"*) ;;
    *) printf 'Add %s to PATH before running sandbox.\n' "$bin_root" ;;
  esac
fi

printf '%s\n' "Next: sandbox login https://api.sandbox.0-uk.com"
