#!/usr/bin/env bash
#
# champollion.dev/give — donate compute to low-resource translation
# benchmarks, in one command:
#
#   curl -fsSL champollion.dev/give | bash
#   curl -fsSL champollion.dev/give | bash -s -- --budget 5
#
# What it does (and nothing more):
#   1. Explains itself and asks before doing anything.
#   2. Installs the mt-eval harness if missing (pipx, no sudo —
#      the same installer as champollion.dev/harness).
#   3. Finds your OpenRouter API key, or prompts for one — the key
#      stays on this machine; it is exported for this session and
#      (only if you say yes) saved to a private .env.local here.
#      We never see it. Never share it with anyone — including us.
#   4. Runs the top of the public queue up to your budget
#      (default $2.00). The exact plan and estimated spend are shown
#      and confirmed before a single token is spent. Language eval
#      packs (FSTs etc.) auto-install per run.
#   5. Tells you how to publish your results and where to watch the
#      mesh light up: https://champollion.dev/mesh
#
# Safety posture:
#   - Never uses sudo. Never phones home. Your key goes only into
#     your environment / your local .env.local (chmod 600).
#   - All prompts read from your terminal (/dev/tty); in a
#     non-interactive context nothing is installed or spent unless
#     you passed --yes AND a key is already in the environment.
#   - --dry-run shows the run plan and exits without spending.
#
set -u

BUDGET="2.00"
TOP=""
ASSUME_YES=0
DRY_RUN=0
INSTALLER_URL="https://champollion.dev/harness"
QUEUE_URL="https://champollion.dev/queue.json"

say()  { printf '%s\n' "$*"; }
err()  { printf 'error: %s\n' "$*" >&2; }

while [ $# -gt 0 ]; do
  case "$1" in
    --budget)  shift; BUDGET="${1:-}";;
    --budget=*) BUDGET="${1#*=}";;
    --top)     shift; TOP="${1:-}";;
    --top=*)   TOP="${1#*=}";;
    --yes|-y)  ASSUME_YES=1;;
    --dry-run) DRY_RUN=1;;
    -h|--help)
      sed -n '2,30p' "$0" 2>/dev/null || true
      echo "Usage: give [--budget USD] [--top N] [--dry-run] [--yes]"
      exit 0
      ;;
    *) err "unknown option: $1 (try --help)"; exit 2;;
  esac
  shift
done

case "$BUDGET" in
  ''|*[!0-9.]*) err "--budget must be a number (got: '$BUDGET')"; exit 2;;
esac
if [ -n "$TOP" ]; then
  case "$TOP" in
    *[!0-9]*|'') err "--top must be a positive integer"; exit 2;;
  esac
fi

# ---- interactivity ---------------------------------------------------------
HAVE_TTY=0
if [ -e /dev/tty ] && { : < /dev/tty; } 2>/dev/null; then
  HAVE_TTY=1
fi

ask_yn() {
  # ask_yn "question" -> 0 yes / 1 no. --yes answers everything yes.
  if [ "$ASSUME_YES" -eq 1 ]; then return 0; fi
  if [ "$HAVE_TTY" -eq 0 ]; then return 1; fi
  printf '%s [y/N]: ' "$1" > /dev/tty
  read -r reply < /dev/tty || reply=""
  case "$reply" in y|Y|yes|YES|Yes) return 0;; *) return 1;; esac
}

say ""
say "  champollion.dev/give — donate a few cents of compute to"
say "  low-resource translation benchmarks."
say ""
if [ -n "$TOP" ]; then
  say "  Plan: run the top $TOP item(s) of the public queue."
else
  say "  Plan: run the top of the public queue up to \$$BUDGET (estimated)."
fi
say "  This will, with your confirmation at each step:"
say "    1. install the mt-eval harness if missing (pipx, no sudo)"
say "    2. use your OpenRouter key — or help you add one"
say "    3. show you the exact runs + estimated cost, then run them"
say ""
say "  Your API key stays on this machine. We never see it."
say "  Never share it with anyone — including us."
say ""

if [ "$DRY_RUN" -eq 0 ]; then
  if ! ask_yn "  Continue?"; then
    if [ "$HAVE_TTY" -eq 0 ] && [ "$ASSUME_YES" -eq 0 ]; then
      err "no terminal available for confirmation."
      say "  Non-interactive use needs an explicit opt-in and a key:"
      say "    export OPENROUTER_API_KEY=sk-or-...   # your key, your machine"
      say "    curl -fsSL champollion.dev/give | bash -s -- --budget $BUDGET --yes"
    else
      say "  Cancelled — nothing was installed or spent."
    fi
    exit 1
  fi
fi

# ---- 1. harness ------------------------------------------------------------
ensure_path() {
  case ":$PATH:" in
    *":$HOME/.local/bin:"*) ;;
    *) PATH="$HOME/.local/bin:$PATH"; export PATH;;
  esac
}
ensure_path

if ! command -v mt-eval >/dev/null 2>&1; then
  say ""
  say "  → mt-eval not found; installing the harness (no sudo)…"
  tmp_installer="$(mktemp -t champollion-harness.XXXXXX)" || {
    err "mktemp failed"; exit 1; }
  if ! curl -fsSL "$INSTALLER_URL" -o "$tmp_installer"; then
    err "could not download the installer from $INSTALLER_URL"
    rm -f "$tmp_installer"; exit 1
  fi
  bash "$tmp_installer"
  installer_rc=$?
  rm -f "$tmp_installer"
  ensure_path
  hash -r 2>/dev/null || true
  if [ $installer_rc -ne 0 ] || ! command -v mt-eval >/dev/null 2>&1; then
    err "harness install did not complete (mt-eval still not on PATH)."
    say "  Open a new terminal and re-run, or install manually:"
    say "    curl -fsSL champollion.dev/harness | bash"
    exit 1
  fi
  say "  ✓ harness installed"
else
  say "  ✓ harness already installed ($(command -v mt-eval))"
fi

# ---- 2. key ----------------------------------------------------------------
have_key=0
if [ -n "${OPENROUTER_API_KEY:-}" ]; then
  have_key=1
  say "  ✓ using OPENROUTER_API_KEY from your environment"
else
  # the harness also searches .env.local / .env upward from here
  d="$PWD"
  while [ -n "$d" ] && [ "$d" != "/" ]; do
    for f in "$d/.env.local" "$d/.env"; do
      if [ -f "$f" ] && grep -q '^OPENROUTER_API_KEY=' "$f" 2>/dev/null; then
        have_key=1
        say "  ✓ found a key in $f (stays on this machine)"
        break 2
      fi
    done
    d="${d%/*}"
  done
fi

if [ "$have_key" -eq 0 ] && [ "$DRY_RUN" -eq 1 ]; then
  say "  (dry run — key not needed to show the plan)"
elif [ "$have_key" -eq 0 ]; then
  if [ "$HAVE_TTY" -eq 0 ]; then
    err "no OpenRouter key found and no terminal to ask for one."
    say "  Get a key at https://openrouter.ai/keys (a few dollars of"
    say "  credit funds hundreds of runs), then:"
    say "    export OPENROUTER_API_KEY=sk-or-...
    curl -fsSL champollion.dev/give | bash -s -- --budget $BUDGET --yes"
    exit 1
  fi
  say ""
  say "  You need an OpenRouter API key (https://openrouter.ai/keys)."
  say "  It is like a prepaid card number for model time: it stays on"
  say "  YOUR machine, we never see it, and you can delete it on the"
  say "  OpenRouter site at any moment."
  printf '  Paste your key (input hidden): ' > /dev/tty
  # shellcheck disable=SC2162
  read -s key_input < /dev/tty; printf '\n' > /dev/tty
  case "$key_input" in
    sk-or-*) ;;
    "") err "no key entered."; exit 1;;
    *) say "  (note: OpenRouter keys usually start with sk-or-…)";;
  esac
  OPENROUTER_API_KEY="$key_input"
  export OPENROUTER_API_KEY
  unset key_input
  if ask_yn "  Save it to $PWD/.env.local (private file, chmod 600) so future runs find it?"; then
    touch .env.local && chmod 600 .env.local
    printf 'OPENROUTER_API_KEY=%s\n' "$OPENROUTER_API_KEY" >> .env.local
    say "  ✓ saved (delete the line in .env.local to remove it)"
  else
    say "  ✓ key kept in this session only"
  fi
fi

# ---- 3. run the queue ------------------------------------------------------
say ""
if [ -n "$TOP" ]; then
  select_args="--top $TOP"
else
  select_args="--budget $BUDGET"
fi
say "  → mt-eval queue $select_args"
say "    (the exact runs and estimated cost are shown next; nothing is"
say "     spent until you confirm. Eval packs like FSTs auto-install.)"
say ""

# shellcheck disable=SC2086
if [ "$DRY_RUN" -eq 1 ]; then
  mt-eval queue $select_args --queue "$QUEUE_URL" --dry-run
  rc=$?
elif [ "$ASSUME_YES" -eq 1 ]; then
  mt-eval queue $select_args --queue "$QUEUE_URL" --yes
  rc=$?
elif [ "$HAVE_TTY" -eq 1 ]; then
  mt-eval queue $select_args --queue "$QUEUE_URL" < /dev/tty
  rc=$?
else
  err "no terminal for the spend confirmation (and --yes not given)."
  exit 1
fi

say ""
if [ $rc -eq 0 ] && [ "$DRY_RUN" -eq 0 ]; then
  say "  Done! Two follow-ups, whenever you like:"
  say "    • publish your reports (your name on the public map):"
  say "        mt-eval publish eval/logs/harness/run_*_report.json"
  say "      Publishing asks you to sign in once (OAuth) so the result"
  say "      is attributed to you — running never requires an account."
  say "    • watch the line you just lit up: https://champollion.dev/mesh"
  say ""
  say "  Changed your mind about any of it?"
  say "    pipx uninstall mt-eval-harness    # removes the harness entirely"
  say "    (and delete your key at openrouter.ai/keys — then nothing can"
  say "     ever be spent again)"
elif [ "$DRY_RUN" -eq 1 ]; then
  say "  That was the plan — nothing was spent. Re-run without --dry-run"
  say "  when ready."
fi
exit $rc
