#!/usr/bin/env bash
# Human01 setup for Gemini CLI (macOS / Linux).
# Saves GEMINI_API_KEY and GOOGLE_GEMINI_BASE_URL in ~/.gemini/.env so Gemini CLI
# talks to Human01. Other lines in that file are kept and the file is backed up
# first. The API key is taken from HUMAN01_API_KEY or entered with hidden input.
set -euo pipefail

# --- 1. Detect Gemini CLI ----------------------------------------------------
if ! command -v gemini >/dev/null 2>&1; then
  echo "Gemini CLI was not found on PATH. Install it (https://github.com/google-gemini/gemini-cli), open a new terminal, and run this script again. No config changes were made." >&2
  exit 127
fi
gemini_version="$(gemini --version 2>/dev/null | head -n1)" || true
gemini_version="${gemini_version:-(installed)}"
printf 'Detected Gemini CLI: %s\n' "${gemini_version}"

# --- 2. API key (env var or hidden prompt) -------------------------------------
api_key="${HUMAN01_API_KEY:-}"
if [[ -z "$api_key" ]]; then
  read -rsp "Human01 API key (input hidden; saved in ~/.gemini/.env): " api_key
  echo
fi
if [[ -z "$api_key" || "$api_key" =~ [[:space:]\"\'\\] ]]; then
  echo "No valid API key provided. No changes were made." >&2
  exit 1
fi

# --- 3. Update ~/.gemini/.env (backup + atomic write) ---------------------------
env_dir="$HOME/.gemini"
env_file="$env_dir/.env"
mkdir -p "$env_dir"
umask 077
tmp="$(mktemp "$env_dir/.env.human01-XXXXXX")"
trap 'rm -f "$tmp"' EXIT
if [[ -f "$env_file" ]]; then
  backup="$env_file.backup-$(date -u +%Y%m%dT%H%M%SZ)"
  cp -p "$env_file" "$backup"
  echo "Backup: $backup"
  grep -vE '^[[:space:]]*(export[[:space:]]+)?(GEMINI_API_KEY|GOOGLE_GEMINI_BASE_URL)=' "$env_file" > "$tmp" || true
fi
{
  printf 'GEMINI_API_KEY=%s\n' "$api_key"
  printf 'GOOGLE_GEMINI_BASE_URL=%s\n' "https://llm.human01.xyz"
} >> "$tmp"
chmod 600 "$tmp"
mv "$tmp" "$env_file"
trap - EXIT

echo "Human01 endpoint and key saved to $env_file"

# --- 4. Human01 lifecycle hooks (session handshake, pinned notes, warnings) ----
if command -v node >/dev/null 2>&1; then
  settings="$env_dir/settings.json"
  hook_script="$env_dir/human01.mjs"
  if curl -fsSL "https://llm.human01.xyz/claude-code-plugin/scripts/human01.mjs" -o "$hook_script"; then
    [[ -f "$settings" ]] && cp -p "$settings" "$settings.backup-$(date -u +%Y%m%dT%H%M%SZ)"
    node -e 'const fs=require("fs");const f=process.argv[1];let j={};try{j=JSON.parse(fs.readFileSync(f,"utf8"))}catch{}const c=`node "${process.argv[2]}" hook`;j.hooks=j.hooks||{};for(const e of ["SessionStart","PreCompress"]){const g=j.hooks[e]=j.hooks[e]||[];if(!JSON.stringify(g).includes(c))g.push({matcher:"*",hooks:[{name:"human01",type:"command",command:c,timeout:5000}]})}fs.writeFileSync(f,JSON.stringify(j,null,2))' "$settings" "$hook_script"
    echo "Human01 hooks added to $settings."
  else
    echo "Skipped the Human01 hooks: could not download the hook script."
  fi
else
  echo "Skipped the Human01 hooks: it needs Node.js."
fi

echo "Start Gemini CLI, choose \"Use Gemini API key\", and pick a Human01 model, for example: gemini -m gpt-6-luna"
