#!/usr/bin/env sh
set -eu

claude_dir="$HOME/.claude"
settings_path="$claude_dir/settings.json"

printf '%s' 'Paste your Claude Code API key: '
if [ -t 0 ]; then stty -echo; fi
IFS= read -r CLAUDE_CODE_API_KEY
if [ -t 0 ]; then stty echo; printf '\n'; fi

if [ -z "${CLAUDE_CODE_API_KEY}" ]; then
  printf '%s\n' 'No API key was entered. Configuration was not changed.' >&2
  exit 1
fi

mkdir -p "$claude_dir"
export CLAUDE_CODE_API_KEY

if command -v node >/dev/null 2>&1; then
  node - "$settings_path" <<'NODE'
const fs = require('fs');
const path = process.argv[2];
let settings = {};
if (fs.existsSync(path)) settings = JSON.parse(fs.readFileSync(path, 'utf8'));
settings.env = settings.env || {};
Object.assign(settings.env, {
  ANTHROPIC_BASE_URL: 'https://blackaicoding.com',
  ANTHROPIC_AUTH_TOKEN: process.env.CLAUDE_CODE_API_KEY.trim(),
  CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC: '1',
  CLAUDE_CODE_ATTRIBUTION_HEADER: '0'
});
fs.writeFileSync(path, `${JSON.stringify(settings, null, 2)}\n`, { mode: 0o600 });
NODE
elif command -v python3 >/dev/null 2>&1; then
  python3 - "$settings_path" <<'PY'
import json, os, sys
path = sys.argv[1]
try:
    with open(path, encoding='utf-8') as source:
        settings = json.load(source)
except FileNotFoundError:
    settings = {}
env = settings.setdefault('env', {})
env.update({
    'ANTHROPIC_BASE_URL': 'https://blackaicoding.com',
    'ANTHROPIC_AUTH_TOKEN': os.environ['CLAUDE_CODE_API_KEY'].strip(),
    'CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC': '1',
    'CLAUDE_CODE_ATTRIBUTION_HEADER': '0',
})
with open(path, 'w', encoding='utf-8') as target:
    json.dump(settings, target, indent=2)
    target.write('\n')
os.chmod(path, 0o600)
PY
else
  printf '%s\n' 'Node.js or Python 3 is required to update settings.json.' >&2
  exit 1
fi
unset CLAUDE_CODE_API_KEY

printf '%s\n' "Claude Code has been configured: $settings_path"
printf '%s\n' 'Restart Claude Code to apply the new settings.'
