#!/usr/bin/env bash
set -euo pipefail
BASE="https://heyelab.com/tokendome"
DEST="$HOME/.tokendome"
TOKEN="${TOKENDOME_TOKEN:-}"
INSTALL_CODE="${TOKENDOME_INSTALL_CODE:-}"
WANT_SERVICE="${TOKENDOME_SERVICE:-0}"

# Prefer the short-lived install code over a raw token. The long-lived
# agent token then never appears in shell history or terminal scrollback.
if [ -n "$INSTALL_CODE" ] && [ -z "$TOKEN" ]; then
  echo "↻ Exchanging install code for agent token …"
  RESP=$(curl -fsSL "$BASE/api/install?exchange=$INSTALL_CODE") || {
    echo "✘ Install code exchange failed (expired, used, or wrong)" >&2
    exit 1
  }
  TOKEN=$(printf '%s' "$RESP" | sed -n 's/.*"user_id":\([0-9]*\).*"agent_token":"\([^"]*\)".*/\1.\2/p')
  if [ -z "$TOKEN" ]; then
    echo "✘ Could not parse install-code exchange response" >&2
    exit 1
  fi
fi

mkdir -p "$DEST"
echo "↓ Downloading agent from $BASE/tokendome.js …"
curl -fsSL "$BASE/tokendome.js" -o "$DEST/tokendome.js"

cat > "$DEST/tokendome" <<EOF
#!/usr/bin/env bash
exec node "$DEST/tokendome.js" "\$@"
EOF
chmod +x "$DEST/tokendome"

# Add to PATH in the user's shell rc, idempotently.
add_to_rc() {
  local rc="$1"
  [ -f "$rc" ] || return 0
  if ! grep -q '\.tokendome' "$rc" 2>/dev/null; then
    {
      echo ''
      echo '# THE TOKENDOME — agent path'
      echo 'export PATH="$HOME/.tokendome:$PATH"'
    } >> "$rc"
    echo "✓ Added $HOME/.tokendome to PATH in $rc"
  fi
}
add_to_rc "$HOME/.zshrc"
add_to_rc "$HOME/.bashrc"

export PATH="$DEST:$PATH"

# Auto-login if a token was provided (or just exchanged from an install code)
if [ -n "$TOKEN" ]; then
  "$DEST/tokendome" login "$TOKEN" "$BASE" >/dev/null
  echo "✓ Logged in"
fi

# Optionally install as a user service so it auto-starts on login
if [ "$WANT_SERVICE" = "1" ]; then
  "$DEST/tokendome" service install
else
  echo ""
  echo "Run the proxy in foreground:   $DEST/tokendome start"
  echo "Or install it as a service:    $DEST/tokendome service install"
fi

echo ""
echo "Point your tools at the proxy:"
echo "  export OPENAI_BASE_URL=\"http://localhost:4000/v1\""
echo "  export ANTHROPIC_BASE_URL=\"http://localhost:4000\""
echo "  export OLLAMA_HOST=\"http://localhost:4000\""
echo ""
echo "✓ Done. Open a new shell or \"source\" your rc to pick up the PATH update."
