#!/bin/sh
set -eu

BASE_URL='https://api.yukon.org'
BIN_DIR="${YUKON_BIN_DIR:-$HOME/.local/bin}"
LIB_DIR="${YUKON_LIB_DIR:-$HOME/.local/share/yukon}"
CLI_PATH="$LIB_DIR/yukon.js"
CLI_BIN="$BIN_DIR/yukon"

say() { printf '%s\n' "$1"; }
fail() { printf 'error: %s\n' "$1" >&2; exit 1; }
shell_quote() { printf "'%s'" "$(printf '%s' "$1" | sed "s/'/'\\''/g")"; }
curl_file() {
  url=$1
  output=$2
  if curl --retry 8 --retry-all-errors --connect-timeout 20 --tls-max 1.2 -fsSL "$url" -o "$output"; then return 0; fi
  if curl --retry 8 --connect-timeout 20 --tls-max 1.2 -fsSL "$url" -o "$output"; then return 0; fi
  curl --retry 8 --connect-timeout 20 -fsSL "$url" -o "$output"
}

command -v curl >/dev/null 2>&1 || fail 'curl is required to install Yukon CLI'
command -v sed >/dev/null 2>&1 || fail 'sed is required to install Yukon CLI'

if command -v bun >/dev/null 2>&1; then
  BUN_PATH=$(command -v bun)
else
  command -v bash >/dev/null 2>&1 || fail 'bash is required to install Bun'
  say 'Bun is required for the Yukon CLI. Installing Bun...'
  curl -fsSL https://bun.sh/install | bash
  if [ -x "$HOME/.bun/bin/bun" ]; then
    BUN_PATH="$HOME/.bun/bin/bun"
  elif command -v bun >/dev/null 2>&1; then
    BUN_PATH=$(command -v bun)
  else
    fail 'Bun install finished, but bun was not found. Add ~/.bun/bin to PATH and rerun this installer.'
  fi
fi

mkdir -p "$BIN_DIR" "$LIB_DIR"
TMP_FILE="$CLI_PATH.tmp.$$"
trap 'rm -f "$TMP_FILE"' EXIT HUP INT TERM
say "Downloading Yukon CLI from $BASE_URL..."
curl_file "$BASE_URL/cli/yukon.js" "$TMP_FILE"
[ -s "$TMP_FILE" ] || fail "downloaded CLI payload is empty"
if command -v mlxfast >/dev/null 2>&1; then
  say 'Uninstalling existing mlxfast CLI...'
  mlxfast uninstall
fi
mv "$TMP_FILE" "$CLI_PATH"

{
  printf '%s\n' '#!/bin/sh'
  printf 'if [ -z "${YUKON_API_URL:-}" ]; then export YUKON_API_URL=%s; fi\n' "$(shell_quote "$BASE_URL")"
  printf 'exec %s %s "$@"\n' "$(shell_quote "$BUN_PATH")" "$(shell_quote "$CLI_PATH")"
} > "$CLI_BIN"
chmod +x "$CLI_BIN"

COMPATIBILITY_CLI_BIN="$BIN_DIR/hilbert"
{
  printf '%s\n' '#!/bin/sh'
  printf 'if [ -z "${YUKON_API_URL:-}" ]; then export YUKON_API_URL=%s; fi\n' "$(shell_quote "$BASE_URL")"
  printf 'exec %s %s "$@"\n' "$(shell_quote "$BUN_PATH")" "$(shell_quote "$CLI_PATH")"
} > "$COMPATIBILITY_CLI_BIN"
chmod +x "$COMPATIBILITY_CLI_BIN"
say "Installed compatibility command hilbert to $COMPATIBILITY_CLI_BIN"

say "Installed yukon to $CLI_BIN"
if [ "${YUKON_INSTALL_SKILL:-1}" != "0" ]; then
  "$CLI_BIN" install-skill
fi

say 'CLI telemetry is enabled after login. Disable it with: yukon config --telemetry disabled'
say 'Trace collection is enabled. CLI commands sync the calling agent native transcript.'
say 'Common secret formats are redacted on a best-effort basis before upload.'
if ! command -v yukon >/dev/null 2>&1; then
  say "Add $BIN_DIR to your PATH to run yukon from any shell."
fi
say 'Done. Try: yukon --help'
