#!/bin/bash

# omarchy:summary=Point Claude Code at a third-party API key and model, or remove that setup
# omarchy:args=[--remove]
# omarchy:examples=omarchy setup claude-api | omarchy setup claude-api --remove

set -euo pipefail

settings="$HOME/.claude/settings.json"
keys=(ANTHROPIC_BASE_URL ANTHROPIC_AUTH_TOKEN ANTHROPIC_MODEL ANTHROPIC_DEFAULT_OPUS_MODEL
  ANTHROPIC_DEFAULT_SONNET_MODEL ANTHROPIC_DEFAULT_HAIKU_MODEL CLAUDE_CODE_SUBAGENT_MODEL)

keys_json=$(printf '%s\n' "${keys[@]}" | jq -R . | jq -s .)

# rewrite <file> <jq filter> [jq args...] replaces the file with a fresh 0600 copy.
rewrite() {
  local file=$1 filter=$2 tmp
  shift 2
  mkdir -p "${file%/*}"
  [[ -f $file ]] || echo '{}' >"$file"
  tmp=$(mktemp "$file.XXXXXX")
  jq --argjson keys "$keys_json" "$@" "$filter" "$file" >"$tmp" || { rm -f "$tmp"; exit 1; }
  mv "$tmp" "$file"
}

if [[ ${1:-} == "--remove" ]]; then
  if [[ -f $settings ]]; then
    rewrite "$settings" 'if .env then .env |= delpaths($keys | map([.])) | if .env == {} then del(.env) end end'
  fi
  echo "Claude Code third-party API removed from $settings"
  exit 0
fi

provider=$(gum choose --header "Claude Code API provider" DeepSeek "Kimi Code" "GLM (Zhipu)" MiniMax Custom)
case "$provider" in
DeepSeek) base_url="https://api.deepseek.com/anthropic" model="deepseek-flash[1m]" key_url="https://platform.deepseek.com/api_keys" ;;
"Kimi Code") base_url="https://api.kimi.com/coding/" model="kimi-for-coding" key_url="https://www.kimi.com/code" ;;
"GLM (Zhipu)") base_url="https://open.bigmodel.cn/api/anthropic" model="glm-5.3[1m]" key_url="https://open.bigmodel.cn/usercenter/apikeys" ;;
MiniMax) base_url="https://api.minimaxi.com/anthropic" model="MiniMax-M3[1m]" key_url="https://platform.minimaxi.com/user-center/basic-information/interface-key" ;;
Custom)
  base_url=$(gum input --header "Anthropic-compatible base URL" --placeholder "https://example.com/anthropic")
  model=""
  key_url=""
  ;;
esac

key=$(gum input --password --header "$provider API key${key_url:+ ($key_url)}")
model=$(gum input --header "Model for every Claude Code tier" --value "$model")

if [[ -z $base_url || -z $key || -z $model ]]; then
  echo "Base URL, API key and model are all required" >&2
  exit 1
fi

rewrite "$settings" '.env = (.env // {}) + ([$keys[] | {key: ., value: $model}] | from_entries) + {ANTHROPIC_BASE_URL: $url, ANTHROPIC_AUTH_TOKEN: $token}' \
  --arg url "$base_url" --arg token "$key" --arg model "$model"

# Third-party keys skip Anthropic's sign-in screen.
rewrite "$HOME/.claude.json" '.hasCompletedOnboarding = true'

echo "Claude Code now uses $model at $base_url"
