#!/usr/bin/env bash
# Human01 setup for Codex CLI (macOS / Linux).
# Adds a "human01" model provider (OpenAI Responses API) to ~/.codex/config.toml
# and stores your API key in a private file that Codex reads through its
# documented command-based provider auth. Your default model and other providers
# are not changed, and the config is backed up first. The API key is taken from
# HUMAN01_API_KEY or entered with hidden input.
set -euo pipefail

endpoint="https://llm.human01.xyz/v1"
launch_command="codex -c model_provider=human01 -m gpt-6-luna"

# --- 1. Detect Codex ---------------------------------------------------------
if ! command -v codex >/dev/null 2>&1; then
  echo "Codex CLI was not found on PATH. Install it (https://developers.openai.com/codex/cli), open a new terminal, and run this script again. No config changes were made." >&2
  exit 127
fi
# A Codex launcher can read stdin, which still carries the script in curl | bash.
if ! codex_version="$(codex --version </dev/null 2>/dev/null)"; then
  echo "Codex CLI was found at $(command -v codex), but it could not start. Run 'codex --version' in this terminal for details. If you are using WSL, install Codex inside your Linux distribution. No config changes were made." >&2
  exit 1
fi
codex_version="${codex_version%%$'\n'*}"
printf 'Detected %s\n' "${codex_version:-Codex CLI}"

# --- 2. Locate config; leave an existing human01 provider alone --------------------
codex_home="${CODEX_HOME:-$HOME/.codex}"
config="$codex_home/config.toml"
key_file="$codex_home/human01-api-key"
if [[ "$codex_home" == *\'* ]]; then
  echo "The Codex home path contains a single quote, which this script cannot write safely. No changes were made." >&2
  exit 1
fi
if [[ -f "$config" ]]; then
  provider_status="$(awk -v endpoint="$endpoint" '
    /^[[:space:]]*\[/ {
      in_provider = /^[[:space:]]*\[model_providers\.human01\][[:space:]]*(#.*)?$/
      if (in_provider || /^[[:space:]]*\[model_providers\.human01\./) found = 1
    }
    in_provider && /^[[:space:]]*base_url[[:space:]]*=/ {
      url = $0
      sub(/^[^=]*=[[:space:]]*/, "", url)
      sub(/[[:space:]]*(#.*)?$/, "", url)
      current = (url == "\"" endpoint "\"" || url == "\047" endpoint "\047" ||
                 url == "\"" endpoint "/\"" || url == "\047" endpoint "/\047")
    }
    END { if (found) print (current ? "current" : "other") }
  ' "$config")"
  case "$provider_status" in
    current)
      printf 'Human01 is already configured in %s.\nUse Codex with: %s\n' "$config" "$launch_command"
      exit 0
      ;;
    other)
      printf 'Human01 already has a provider entry in %s. To use this gateway, set its base_url to %s. No config changes were made.\n' "$config" "$endpoint" >&2
      exit 1
      ;;
  esac
fi

# --- 3. API key (env var or hidden prompt) -------------------------------------
api_key="${HUMAN01_API_KEY:-}"
if [[ -z "$api_key" ]]; then
  # In curl | bash, stdin carries the script. Read credentials from the terminal.
  if ! { exec 3</dev/tty; } 2>/dev/null; then
    echo "No interactive terminal is available. Run this installer in a terminal or set HUMAN01_API_KEY before running it. No changes were made." >&2
    exit 1
  fi
  read -rsp "Human01 API key (input hidden; saved in $key_file): " api_key <&3 || api_key=""
  exec 3<&-
  printf '\n' >&2
fi
if [[ -z "$api_key" || "$api_key" =~ [[:space:]] ]]; then
  echo "No valid API key provided. No changes were made." >&2
  exit 1
fi

# --- 4. Write key file and provider table (backup first) ------------------------
mkdir -p "$codex_home"
umask 077
printf '%s\n' "$api_key" > "$key_file"
chmod 600 "$key_file"
if [[ -f "$config" ]]; then
  backup="$config.backup-$(date -u +%Y%m%dT%H%M%SZ)"
  cp -p "$config" "$backup"
  echo "Backup: $backup"
  [[ -s "$config" && "$(tail -c1 "$config" | wc -l)" -eq 0 ]] && printf '\n' >> "$config"
fi
cat >> "$config" <<EOF

[model_providers.human01]
name = "Human01"
base_url = "$endpoint"
wire_api = "responses"

[model_providers.human01.auth]
command = "cat"
args = ['$key_file']
EOF

echo "Human01 provider added to $config (key stored in $key_file)"

# --- 5. Human01 lifecycle hooks (session handshake, pinned notes, warnings) ----
if command -v node >/dev/null 2>&1; then
  hooks_file="$codex_home/hooks.json"
  if curl -fsSL "https://llm.human01.xyz/claude-code-plugin/scripts/human01.mjs" -o "$codex_home/human01.mjs"; then
    if [[ -f "$hooks_file" ]]; then
      backup="$hooks_file.backup-$(date -u +%Y%m%dT%H%M%SZ)"
      cp -p "$hooks_file" "$backup"
    fi
    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`;for(const e of ["SessionStart","UserPromptSubmit","PreCompact"]){j.hooks=j.hooks||{};const g=j.hooks[e]=j.hooks[e]||[];if(!JSON.stringify(g).includes(c))g.push({matcher:e==="SessionStart"?"startup|resume|clear|compact":"*",hooks:[{type:"command",command:c,timeout:5}]})}fs.writeFileSync(f,JSON.stringify(j,null,2))' "$hooks_file" "$codex_home/human01.mjs"
    echo "Human01 hooks added to $hooks_file (trust them in Codex with /hooks)."
  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 "Use Codex with: $launch_command"
