#!/usr/bin/env bash
# Human01 setup for Aider (macOS / Linux).
# Saves openai-api-base and openai-api-key in ~/.aider.conf.yml so Aider talks to
# Human01. Other settings 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 Aider -----------------------------------------------------------
if ! command -v aider >/dev/null 2>&1; then
  echo "Aider was not found on PATH. Install it (https://aider.chat/docs/install.html), open a new terminal, and run this script again. No config changes were made." >&2
  exit 127
fi
aider_version="$(aider --version 2>/dev/null | head -n1)" || true
aider_version="${aider_version:-(installed)}"
printf 'Detected Aider: %s\n' "${aider_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 ~/.aider.conf.yml): " 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 ~/.aider.conf.yml (backup + atomic write) ------------------------
conf="$HOME/.aider.conf.yml"
umask 077
tmp="$(mktemp "$HOME/.aider.conf.yml.human01-XXXXXX")"
trap 'rm -f "$tmp"' EXIT
if [[ -f "$conf" ]]; then
  backup="$conf.backup-$(date -u +%Y%m%dT%H%M%SZ)"
  cp -p "$conf" "$backup"
  echo "Backup: $backup"
  grep -vE '^(openai-api-base|openai-api-key):' "$conf" > "$tmp" || true
fi
{
  printf 'openai-api-base: "%s"\n' "https://llm.human01.xyz/v1"
  printf 'openai-api-key: "%s"\n' "$api_key"
} >> "$tmp"
chmod 600 "$tmp"
mv "$tmp" "$conf"
trap - EXIT

echo "Human01 endpoint and key saved to $conf"
echo "Run Aider with the openai/ prefix on any Human01 model, for example: aider --model openai/claude-sonnet-5-5"
