#!/usr/bin/env bash
# osbot — query the live OS-BOT network agent from Termux / any shell
# Install:  curl -fsSL "https://nodeweaverapp.com/api/os-bot.sh" -o /tmp/osbot.sh && bash /tmp/osbot.sh install
# One-shot: curl -fsSL "https://nodeweaverapp.com/api/os-bot.sh" | bash -s -- "what's connected?"
set -euo pipefail

OSBOT_ENDPOINT="${OSBOT_ENDPOINT:-https://nodeweaverapp.com/api/os-bot}"

ask() {
  local q="$*"
  if [ -z "$q" ]; then
    echo "usage: osbot <question>" >&2
    exit 1
  fi
  # URL-encode via jq if available, else fall back to python
  if command -v jq >/dev/null 2>&1; then
    encoded=$(printf '%s' "$q" | jq -sRr @uri)
  else
    encoded=$(python3 -c "import urllib.parse,sys;print(urllib.parse.quote(sys.argv[1]))" "$q")
  fi
  curl -fsSL "${OSBOT_ENDPOINT}?q=${encoded}"
}

install_self() {
  local bin_dir="${HOME}/bin"
  mkdir -p "$bin_dir"
  local target="${bin_dir}/osbot"
  curl -fsSL "https://nodeweaverapp.com/api/os-bot.sh" -o "$target"
  chmod +x "$target"
  case ":$PATH:" in
    *":$bin_dir:"*) ;;
    *) echo 'export PATH="$HOME/bin:$PATH"' >> "${HOME}/.bashrc" ;;
  esac
  echo "✓ Installed: $target"
  echo "  Try: osbot 'any threats?'"
}

case "${1:-}" in
  install) install_self ;;
  "") echo "usage: osbot <question> | osbot install" >&2; exit 1 ;;
  *) ask "$@" ;;
esac
