#!/usr/bin/env bash
# gawd.sh/start — bring your Gawd to life in one command.
#
#   curl -fsSL https://gawd.sh/start | bash
#   curl -fsSL https://gawd.sh/start | GAWD_PROVIDER=minimax bash
#
# Run step 1 first (curl -fsSL https://gawd.sh/install | bash). This finds your
# vault, asks for any secret it still needs (bot token + provider key), validates
# your bot token with Telegram, then runs the daemon. Nothing to put on PATH,
# nothing long to paste, nothing to edit.
#
# Overridable via env: GAWD_PROVIDER (default deepseek), GAWD_CONTAINER (gawd),
# GAWD_IMAGE (ghcr.io/gawd-sh/gawd:latest), GAWD_DATA ($HOME/.gawd).

set -uo pipefail

PROVIDER="${GAWD_PROVIDER:-deepseek}"
CONTAINER="${GAWD_CONTAINER:-gawd}"
IMAGE="${GAWD_IMAGE:-ghcr.io/gawd-sh/gawd:latest}"
DATA="${GAWD_DATA:-$HOME/.gawd}"

c_gold=$'\033[1;33m'; c_red=$'\033[1;31m'; c_grn=$'\033[1;32m'; c_off=$'\033[0m'
say(){ printf '%s[gawd]%s %s\n' "$c_gold" "$c_off" "$*"; }
ok(){  printf '%s[gawd] OK%s %s\n' "$c_grn" "$c_off" "$*"; }
die(){ printf '%s[gawd] x %s%s\n' "$c_red" "$*" "$c_off" >&2; exit 1; }

# Map provider -> the API-key vault name it expects.
case "$PROVIDER" in
  deepseek)      KEYVAR=DEEPSEEK_API_KEY ;;
  minimax)       KEYVAR=MINIMAX_API_KEY ;;
  anthropic)     KEYVAR=ANTHROPIC_API_KEY ;;
  openai)        KEYVAR=OPENAI_API_KEY ;;
  gemini)        KEYVAR=GEMINI_API_KEY ;;
  groq)          KEYVAR=GROQ_API_KEY ;;
  kimi|moonshot) PROVIDER=kimi; KEYVAR=MOONSHOT_API_KEY ;;
  gawd|beta)     PROVIDER=gawd; KEYVAR=GAWD_LLM_CODE ;;
  *) die "That AI provider isn't recognized. Supported: deepseek minimax anthropic openai gemini groq kimi gawd" ;;
esac

# House-minted access codes (metered pool, beta program only) are distinguishable
# by a deterministic prefix and are routed to the House proxy regardless of what
# $PROVIDER defaulted to — the key prompt below is the SAME for every installer;
# only the pasted VALUE decides where it routes. This keeps the public path (no
# GAWD_PROVIDER set, or any real provider key) and the House path (a House-minted
# code) on one identical prompt, with no beta-only branch or wording exposed here.
HOUSE_KEY_PREFIX="sk-gawdbeta_"

# --- preflight ---
command -v docker  >/dev/null 2>&1 || die "This device needs Docker installed first: https://docs.docker.com/engine/install/ — then run this again."
docker info        >/dev/null 2>&1 || die "Docker needs to be running. Start it, then run this again."

# Resolve the secrets helper by ABSOLUTE PATH — never depend on it being on $PATH.
# (A freshly-installed ~/.local/bin/secrets is NOT on the current shell's PATH
# until the next login; we must not require the user to re-login or export PATH.)
SECRETS=""
if command -v secrets >/dev/null 2>&1; then SECRETS="$(command -v secrets)"; fi
[ -z "$SECRETS" ] && for p in "$HOME/.local/bin/secrets" /usr/local/bin/secrets; do
  [ -x "$p" ] && { SECRETS="$p"; break; }
done
[ -n "$SECRETS" ] || die "Run Step 1 first:  curl -fsSL https://gawd.sh/install | bash"

# Is the vault ready (age key present)? The helper needs it to store/read secrets.
"$SECRETS" list >/dev/null 2>&1 || die "Step 1 hasn't finished yet. Run it first:  curl -fsSL https://gawd.sh/install | bash"

have_secret(){ "$SECRETS" list 2>/dev/null | grep -x "$1" >/dev/null; }

# Read one line from the terminal even though stdin is the piped script (curl|bash).
TTY=/dev/tty
[ -r "$TTY" ] || die "This needs somewhere to type into. Or set your token first:  $SECRETS set TELEGRAM_BOT_TOKEN"

prompt_secret(){  # $1=vault key  $2=human prompt
  local key="$1" label="$2" val=""
  printf '%s%s%s ' "$c_gold" "$label" "$c_off" > "$TTY"
  IFS= read -rs val < "$TTY"; printf '\n' > "$TTY"
  printf '%s' "$val"
}

# --- Telegram bot token: validate with Telegram BEFORE storing (never store an
# unvalidated token), and self-heal a previously-stored-but-bad token by
# re-prompting instead of dying every subsequent run. Token value is never
# printed; only curl'd directly or piped through the vault helper. ---
validate_token(){  # $1=raw token (not printed) -> prints @username on success, returns 1 on reject
  local tok="$1" getme
  getme="$(curl -s --max-time 15 "https://api.telegram.org/bot${tok}/getMe" 2>/dev/null || true)"
  printf '%s' "$getme" | grep -q '"ok":true' || return 1
  printf '%s' "$getme" | grep -oE '"username":"[^"]+"' | head -1 | cut -d'"' -f4
}

BOT=""
if have_secret TELEGRAM_BOT_TOKEN; then
  say "Checking your saved Telegram bot token..."
  GETME_STORED="$("$SECRETS" env TELEGRAM_BOT_TOKEN -- sh -c 'curl -s --max-time 15 "https://api.telegram.org/bot${TELEGRAM_BOT_TOKEN}/getMe"' 2>/dev/null || true)"
  if printf '%s' "$GETME_STORED" | grep -q '"ok":true'; then
    BOT="$(printf '%s' "$GETME_STORED" | grep -oE '"username":"[^"]+"' | head -1 | cut -d'"' -f4)"
  else
    say "That saved token didn't validate with Telegram. Let's get a fresh one."
  fi
fi

if [ -z "$BOT" ]; then
  say "Let's connect your Telegram bot. Create one with @BotFather (/newbot) and copy its token."
  for attempt in 1 2 3; do
    raw="$(prompt_secret TELEGRAM_BOT_TOKEN 'Paste your Telegram bot token:')"
    # Paste-robust: pull just the digits:hash token out of whatever was pasted.
    tok="$(printf '%s' "$raw" | grep -oE '[0-9]{6,}:[A-Za-z0-9_-]{30,}' | head -1)"
    if [ -z "$tok" ]; then
      say "That didn't look like a bot token. Try again."
      continue
    fi
    if BOT="$(validate_token "$tok")" && [ -n "$BOT" ]; then
      printf '%s' "$tok" | "$SECRETS" set TELEGRAM_BOT_TOKEN >/dev/null 2>&1
      break
    fi
    BOT=""
    say "Telegram didn't accept that bot token. Get a fresh one from @BotFather and try again."
  done
  [ -n "$BOT" ] || die "No valid Telegram bot token provided. Get one from @BotFather and re-run."
fi
ok "Token valid for @${BOT}."

# --- LLM key: one uniform prompt for every installer. If a key is already
# stored (either as a House code, or under the selected provider's own vault
# name) we skip the prompt entirely — this keeps re-installs idempotent. The
# House-code check runs first and applies regardless of what $PROVIDER
# defaulted to, so an installer who already has a House code stays on the
# House path even if GAWD_PROVIDER was never set (or set to something else).
if have_secret GAWD_LLM_CODE; then
  PROVIDER=gawd
  KEYVAR=GAWD_LLM_CODE
elif have_secret "$KEYVAR"; then
  : # already configured for the selected provider — nothing to do
else
  say "Gawd needs an LLM key to think with."
  key="$(prompt_secret LLM_KEY "Paste your LLM key:")"
  [ -n "$key" ] || die "Nothing entered. Paste the key you were given and try again."
  case "$key" in
    ${HOUSE_KEY_PREFIX}*)
      # Deterministic House-minted prefix — route to the House proxy no matter
      # what provider was selected/defaulted above.
      PROVIDER=gawd
      KEYVAR=GAWD_LLM_CODE
      ;;
    *)
      : # not a House code — proceed with the provider $GAWD_PROVIDER selected
        # (default: deepseek), exactly as before.
      ;;
  esac
  printf '%s' "$key" | "$SECRETS" set "$KEYVAR" >/dev/null 2>&1
fi

# --- (re)create the container ---
if docker ps -a --format '{{.Names}}' | grep -qx "$CONTAINER"; then
  say "Getting a clean start ready..."
  docker rm -f "$CONTAINER" >/dev/null 2>&1 || true
fi
mkdir -p "$DATA"
say "Starting Gawd..."
_EXTRA_ENV=""
[ "$PROVIDER" = "gawd" ] && _EXTRA_ENV="-e GAWD_LLM_ENDPOINT=https://llm-beta.gawd.sh/v1"
# shellcheck disable=SC2086
"$SECRETS" env "$KEYVAR" TELEGRAM_BOT_TOKEN -- docker run -d --name "$CONTAINER" \
  --restart unless-stopped \
  -e "GAWD_PROVIDER=$PROVIDER" -e "$KEYVAR" -e TELEGRAM_BOT_TOKEN \
  $_EXTRA_ENV \
  -v "$DATA:/data" "$IMAGE" >/dev/null \
  || die "Something went wrong getting Gawd started. For details:  docker logs $CONTAINER"

say "Finishing setup..."
docker exec "$CONTAINER" bash /usr/local/lib/gawd/install.sh --non-interactive >/dev/null 2>&1 || true
docker restart "$CONTAINER" >/dev/null 2>&1 || true

# --- wait for the gateway to report healthy ---
say "Waking Gawd up..."
healthy=""
for _ in $(seq 1 30); do
  if docker exec "$CONTAINER" sh -c 'curl -s --max-time 3 http://127.0.0.1:18789/health 2>/dev/null' | grep -q '"ok":true'; then
    healthy=1; break
  fi
  sleep 3
done

printf '\n'
if [ -n "$healthy" ]; then
  ok "Gawd is alive."
else
  say "Still getting Gawd running — give it another minute. If it's taking too long:  docker logs $CONTAINER"
fi
cat <<MSG

  ${c_gold}Open Telegram and message @${BOT}.${c_off}
  Your first message claims you as its keeper — no IDs, no config.
  Gawd will answer in voice.

MSG
