#!/usr/bin/env bash
# LotusAI setup for Codex on macOS and Linux.
#
#   curl -fsSL https://lotusai.pro/setup.sh | bash
#
# Optional:
#   curl -fsSL https://lotusai.pro/setup.sh | bash -s -- sk-lotus-...       key without the prompt
#   curl -fsSL https://lotusai.pro/setup.sh | LOTUSAI_MODEL=gpt-6-astra bash
#   curl -fsSL https://lotusai.pro/setup.sh | bash -s -- --uninstall        undo everything below
#
# What it does:
#   1. Asks for your LotusAI key (or reads LOTUSAI_API_KEY from the environment).
#   2. Adds the `lotusai` provider to ~/.codex/config.toml (or $CODEX_HOME) and
#      selects it, inside marked blocks, with your key in the provider block
#      (experimental_bearer_token), so Codex finds it in every terminal, IDE
#      extension and the Codex app. Your other settings and providers stay,
#      the old file is backed up first, and any model / model_provider value it
#      replaces is remembered so --uninstall can put it back.
#   3. Also saves LOTUSAI_API_KEY in your shell profile (a marked block that is
#      replaced on re-runs) for SDKs and curl. Codex itself does not need it.
#   4. Installs the Codex CLI with npm if the `codex` command is missing and
#      Node.js is present.
#   5. Verifies the key against the API.
#
# Safe to run more than once. Nothing is downloaded or executed beyond npm.

set -euo pipefail

API_ORIGIN="https://api.lotusai.pro"
BASE_URL="$API_ORIGIN/v1"
SITE="https://lotusai.pro"
KEY_PREFIX="sk-lotus-"
MODEL="${LOTUSAI_MODEL:-gpt-6.1-sol}"
CODEX_PACKAGE="@openai/codex"
MARK_START="# >>> LotusAI >>>"
MARK_END="# <<< LotusAI <<<"
CODEX_DIR="${CODEX_HOME:-$HOME/.codex}"
CONFIG="$CODEX_DIR/config.toml"

say()  { printf '  %s\n' "$*"; }
ok()   { printf '  \033[32m+\033[0m %s\n' "$*"; }
warn() { printf '  \033[33m!\033[0m %s\n' "$*"; }
fail() { printf '  \033[31mx\033[0m %s\n' "$*" >&2; exit 1; }

printf '\n'
printf '  \033[35mLotusAI\033[0m for Codex\n'
printf '  Coding intelligence that never runs dry.\n\n'

MODE="setup"
ARG_KEY=""
for arg in "$@"; do
  case "$arg" in
    --uninstall|uninstall) MODE="uninstall" ;;
    -*) ;;
    *) ARG_KEY="$arg" ;;
  esac
done

case "$MODEL" in
  *[!A-Za-z0-9._:-]*|"") fail "LOTUSAI_MODEL must be a model id such as gpt-6.1-sol." ;;
esac

# ---------------------------------------------------------------- config editing
# One awk program, two modes. merge: drop the old LotusAI blocks and any
# hand-written [model_providers.lotusai] table, move root `model_provider` and
# `model` into the remembered list, then write the top block, the rest of the
# file and the provider block. unmerge: drop the blocks and put the remembered
# root keys back. Table headers inside multi-line strings are ignored.
read -r -d '' AWK_CONFIG <<'AWK' || true
function trim(s) { sub(/^[ \t]+/, "", s); sub(/[ \t]+$/, "", s); return s }
function keyname(s,   t) { t = trim(s); if (match(t, /^[A-Za-z0-9_-]+[ \t]*=/)) { t = substr(t, 1, RLENGTH); sub(/[ \t]*=$/, "", t); return t } return "" }
function count(s, pat,   n) { n = gsub(pat, "", s); return n }
BEGIN {
  TS = "# >>> LotusAI >>>"; TE = "# <<< LotusAI <<<"
  PS = "# >>> LotusAI provider >>>"; PE = "# <<< LotusAI provider <<<"
  PT = "# lotusai-previous:"
  inblock = ""; instr = ""; skiptable = 0; seen_table = 0
  nrest = 0; nprev = 0; ntaken = 0
}
{
  line = $0; sub(/\r$/, "", line); t = trim(line)
  if (inblock == "" && (t == TS || t == PS)) { inblock = (t == TS) ? TE : PE; next }
  if (inblock != "") {
    if (t == inblock) { inblock = ""; next }
    if (index(t, PT) == 1) { prev[++nprev] = trim(substr(t, length(PT) + 1)) }
    next
  }
  # Dotted keys, each bare or quoted; quoted keys may hold any character
  # (Windows paths in [projects."C:\\work"]). No backslash inside brackets:
  # awks disagree on what it means there.
  header = (instr == "" && line ~ /^[ \t]*\[\[?[ \t]*([A-Za-z0-9_-]+|"([^"]|\\")*"|'[^']*')([ \t]*\.[ \t]*([A-Za-z0-9_-]+|"([^"]|\\")*"|'[^']*'))*[ \t]*\]\]?[ \t]*(#.*)?$/)
  dq = count(line, "\"\"\""); sq = count(line, "'''")
  if (dq % 2 == 1) { if (instr == "") instr = "dq"; else if (instr == "dq") instr = "" }
  if (sq % 2 == 1) { if (instr == "") instr = "sq"; else if (instr == "sq") instr = "" }
  if (header) {
    seen_table = 1
    skiptable = (mode == "merge" && line ~ /^[ \t]*\[[ \t]*model_providers[ \t]*\.[ \t]*("lotusai"|lotusai|'lotusai')[ \t]*\][ \t]*(#.*)?$/)
  }
  if (skiptable) next
  k = keyname(line)
  if (mode == "merge" && !seen_table && (k == "model_provider" || k == "model")) { taken[++ntaken] = t; next }
  if (!seen_table && k != "") present[k] = 1
  rest[++nrest] = line
}
END {
  a = 1; while (a <= nrest && trim(rest[a]) == "") a++
  b = nrest; while (b >= a && trim(rest[b]) == "") b--
  if (mode == "merge") {
    nkeep = 0
    for (i = 1; i <= nprev; i++) { k = keyname(prev[i]); if (k != "") { remember[k] = prev[i]; order[++nkeep] = k } }
    for (i = 1; i <= ntaken; i++) { k = keyname(taken[i]); if (k != "") { if (!(k in remember)) order[++nkeep] = k; remember[k] = taken[i] } }
    print TS
    print "# Added by the LotusAI installer. Remove with: npx lotusai uninstall"
    for (i = 1; i <= nkeep; i++) {
      k = order[i]
      if (k in done) continue
      done[k] = 1
      if (k == "model_provider" && index(remember[k], "\"lotusai\"") > 0) continue
      print PT " " remember[k]
    }
    print "model_provider = \"lotusai\""
    print "model = \"" model "\""
    print TE
    if (a <= b) { print ""; for (i = a; i <= b; i++) print rest[i] }
    print ""
    print PS
    print "[model_providers.lotusai]"
    print "name = \"LotusAI\""
    print "base_url = \"" base "\""
    # The key itself, not env_key: Codex reads env_key first and stops with
    # "Missing environment variable" whenever the variable is not in its
    # process, even when a token is present (Codex 0.163.0, October 2026).
    print "experimental_bearer_token = \"" ENVIRON["LOTUSAI_TOML_TOKEN"] "\""
    print "wire_api = \"responses\""
    print "requires_openai_auth = false"
    print PE
  } else {
    nout = 0
    for (i = 1; i <= nprev; i++) { k = keyname(prev[i]); if (k != "" && !(k in present)) { print prev[i]; nout++ } }
    if (nout > 0 && a <= b) print ""
    for (i = a; i <= b; i++) print rest[i]
  }
}
AWK

write_config() {  # $1 = merge | unmerge
  local tmp backup stamp
  mkdir -p "$CODEX_DIR"
  tmp="$(mktemp "$CODEX_DIR/.config.toml.XXXXXX")"
  if [ -f "$CONFIG" ]; then
    LOTUSAI_TOML_TOKEN="${TOML_TOKEN:-}" awk -v mode="$1" -v model="$MODEL" -v base="$BASE_URL" "$AWK_CONFIG" "$CONFIG" > "$tmp"
    stamp="$(date +%Y%m%d-%H%M%S)"
    backup="$CONFIG.lotusai-backup-$stamp"
    cp -p "$CONFIG" "$backup"
    BACKUP="$backup"
  else
    LOTUSAI_TOML_TOKEN="${TOML_TOKEN:-}" awk -v mode="$1" -v model="$MODEL" -v base="$BASE_URL" "$AWK_CONFIG" /dev/null > "$tmp"
    BACKUP=""
  fi
  mv "$tmp" "$CONFIG"
}

# ---------------------------------------------------------------- shell profile
detect_profile() {
  local shell_name
  shell_name="$(basename "${SHELL:-}")"
  case "$shell_name" in
    zsh)  printf '%s' "${ZDOTDIR:-$HOME}/.zshrc" ;;
    fish) printf '%s' "${XDG_CONFIG_HOME:-$HOME/.config}/fish/config.fish" ;;
    bash)
      if [ "$(uname -s)" = "Darwin" ]; then
        printf '%s' "$HOME/.bash_profile"
      else
        printf '%s' "$HOME/.bashrc"
      fi
      ;;
    *) printf '%s' "$HOME/.profile" ;;
  esac
}

# Print a profile without the LotusAI block (command substitution strips the
# trailing newlines, so re-runs never grow the file).
strip_block() {
  awk -v s="$MARK_START" -v e="$MARK_END" '
    $0 == s { skip = 1; next }
    $0 == e { skip = 0; next }
    !skip   { print }
  ' "$1"
}

# ---------------------------------------------------------------- uninstall
if [ "$MODE" = "uninstall" ]; then
  if [ -f "$CONFIG" ] && grep -qF "# >>> LotusAI" "$CONFIG"; then
    write_config unmerge
    if [ -z "$(tr -d '[:space:]' < "$CONFIG")" ]; then rm -f "$CONFIG"; fi
    ok "LotusAI removed from $CONFIG"
    [ -n "$BACKUP" ] && say "Previous config saved as $BACKUP"
  else
    warn "No LotusAI blocks in $CONFIG"
  fi
  removed=0
  for f in "${ZDOTDIR:-$HOME}/.zshrc" "$HOME/.bashrc" "$HOME/.bash_profile" "$HOME/.profile" "${XDG_CONFIG_HOME:-$HOME/.config}/fish/config.fish"; do
    if [ -f "$f" ] && grep -qxF "$MARK_START" "$f"; then
      REST="$(strip_block "$f")"
      if [ -n "$REST" ]; then printf '%s\n' "$REST" > "$f"; else : > "$f"; fi
      ok "LOTUSAI_API_KEY removed from $f"
      removed=1
    fi
  done
  [ "$removed" = 1 ] || warn "No LOTUSAI_API_KEY block in your shell profiles."
  say "The Codex CLI stays installed. Remove it with: npm uninstall -g $CODEX_PACKAGE"
  printf '\n'
  exit 0
fi

# ---------------------------------------------------------------- key
# A key on the command line wins, so `bash -s -- sk-lotus-new` replaces a saved
# one. A key that only comes from the environment after an earlier setup is
# most likely the saved one, so it is shown and kept on Enter, never reused
# silently.
API_KEY="${ARG_KEY:-${LOTUSAI_API_KEY:-}}"
if [ -z "$ARG_KEY" ] && [ -n "$API_KEY" ] && [ -r /dev/tty ] \
  && grep -qxF "$MARK_START" "$(detect_profile)" 2>/dev/null; then
  printf '  Saved key ...%s found. Press Enter to keep it, or paste a new key: ' "${API_KEY: -4}"
  read -r NEW_KEY </dev/tty || NEW_KEY=""
  printf '\n'
  [ -n "$NEW_KEY" ] && API_KEY="$NEW_KEY"
fi
if [ -z "$API_KEY" ]; then
  if [ -r /dev/tty ]; then
    printf '  Paste your LotusAI key (%s...): ' "$KEY_PREFIX"
    read -r API_KEY </dev/tty
    printf '\n'
  else
    fail "No terminal available. Re-run with LOTUSAI_API_KEY=${KEY_PREFIX}... in the environment."
  fi
fi

# Trim whitespace.
API_KEY="$(printf '%s' "$API_KEY" | tr -d '[:space:]')"
[ -n "$API_KEY" ] || fail "The key cannot be empty. Keys come from resellers: $SITE/get-access"
case "$API_KEY" in
  *[!\!-~]*) fail "That key has characters a LotusAI key never has. Copy it again and retry." ;;
esac
case "$API_KEY" in
  "$KEY_PREFIX"*) ;;
  *) warn "Keys normally start with ${KEY_PREFIX}. Continuing with the value you entered." ;;
esac

# ---------------------------------------------------------------- Codex config
# The key as a TOML basic string body (only \ and " need escaping; the key is
# printable ASCII). Passed to awk through the environment, which, unlike -v,
# does not interpret backslashes.
TOML_TOKEN="$(printf '%s' "$API_KEY" | sed -e 's/\\/\\\\/g' -e 's/"/\\"/g')"
write_config merge
chmod 600 "$CONFIG" 2>/dev/null || true
ok "Codex config updated: $CONFIG (model $MODEL, key stored in the lotusai block)"
[ -n "$BACKUP" ] && say "Previous config saved as $BACKUP"

# ---------------------------------------------------------------- shell profile
PROFILE="$(detect_profile)"
mkdir -p "$(dirname "$PROFILE")"
touch "$PROFILE"

# Single quotes keep the shell from expanding anything inside the key.
if [ "$(basename "$PROFILE")" = "config.fish" ]; then
  QUOTED="'$(printf '%s' "$API_KEY" | sed -e 's/\\/\\\\/g' -e "s/'/\\\\'/g")'"
  BLOCK="$(printf '%s\nset -gx LOTUSAI_API_KEY %s\n%s' "$MARK_START" "$QUOTED" "$MARK_END")"
else
  QUOTED="'$(printf '%s' "$API_KEY" | sed "s/'/'\\\\''/g")'"
  BLOCK="$(printf '%s\nexport LOTUSAI_API_KEY=%s\n%s' "$MARK_START" "$QUOTED" "$MARK_END")"
fi

EXISTING="$(strip_block "$PROFILE")"
if [ -n "$EXISTING" ]; then
  printf '%s\n\n%s\n' "$EXISTING" "$BLOCK" > "$PROFILE"
else
  printf '%s\n' "$BLOCK" > "$PROFILE"
fi
chmod 600 "$PROFILE" 2>/dev/null || true
ok "LOTUSAI_API_KEY saved in $PROFILE (for SDKs and curl)"

export LOTUSAI_API_KEY="$API_KEY"

# ---------------------------------------------------------------- Codex CLI
if command -v codex >/dev/null 2>&1; then
  ok "Codex CLI already installed ($(codex --version 2>/dev/null | head -n 1 || printf 'version unknown'))"
elif command -v npm >/dev/null 2>&1; then
  say "Installing the Codex CLI with npm..."
  if npm install -g "$CODEX_PACKAGE" >/dev/null 2>&1; then
    ok "Codex CLI installed"
  else
    warn "npm install failed (permissions?). Try: sudo npm install -g $CODEX_PACKAGE"
  fi
else
  warn "The Codex CLI needs Node.js 18 or newer, and Node.js was not found."
  say "Install Node.js from https://nodejs.org, then run: npm install -g $CODEX_PACKAGE"
  say "Your config and key are already in place, so Codex works as soon as it is installed."
fi

# ---------------------------------------------------------------- verify
printf '\n'
say "Verifying..."
if command -v curl >/dev/null 2>&1; then
  MODELS="$(curl -fsS --max-time 10 -H "Authorization: Bearer $API_KEY" "$BASE_URL/models" 2>/dev/null || true)"
  if printf '%s' "$MODELS" | grep -q '"data"'; then
    if printf '%s' "$MODELS" | grep -q "\"id\":\"$MODEL\""; then
      ok "API reachable, $MODEL is available"
    else
      warn "API reachable, but $MODEL is not in its model list right now. Pick another with /model inside Codex."
    fi
  else
    warn "Could not reach $BASE_URL right now. The setup is saved; check $SITE/status"
  fi

  BODY="$(curl -sS --max-time 10 -H "Authorization: Bearer $API_KEY" "$API_ORIGIN/api/key-status" 2>/dev/null || true)"
  case "$BODY" in
    *'"status":"found"'*)
      if printf '%s' "$BODY" | grep -q '"isExpired":true'; then
        warn "Key recognised, but it has expired. Ask the reseller who issued it to renew it."
      elif printf '%s' "$BODY" | grep -q '"isOverLimit":true'; then
        warn "Key recognised. Its five-hour window is full right now and refills on its own."
      elif printf '%s' "$BODY" | grep -q '"isActive":false'; then
        warn "Key recognised, but it is disabled. Ask the reseller who issued it."
      else
        ok "Key recognised and active"
      fi
      ;;
    *'API key not found'*) warn "The API did not recognise this key. Check it at $SITE/key-status" ;;
    *) warn "Could not check the key right now. Check it any time at $SITE/key-status" ;;
  esac
else
  warn "curl not found, skipped verification."
fi

# ---------------------------------------------------------------- done
printf '\n'
printf '  \033[32mDone.\033[0m\n'
say "Go to your project and run: codex"
say "Default model: $MODEL. Switch any time with /model inside Codex."
say "Check usage any time: $SITE/key-status"
printf '\n'
