#!/bin/bash
# ============================================================
# AICraft - Claude Code Installer
# Installs Claude Code + writes AICraft API config
# Safe: only installs Claude Code and writes settings.json
# ============================================================
set -e

echo ''
echo '  AICraft Claude Code Installer'
echo '  ================================'
echo '  What this does:'
echo '    1. Install Claude Code (Anthropic native installer)'
echo '    2. Write settings.json pointing to AICraft API'
echo '    3. Nothing else - no telemetry, no data collection'
echo ''

# Get API Key
if [ -z "$AICRAFT_API_KEY" ]; then
  echo '  Enter your AICraft API Key'
  echo '  (Get it from https://aicraftapi.com/dashboard.html)'
  read -p '  > ' AK
else
  AK="$AICRAFT_API_KEY"
  echo '  Using AICRAFT_API_KEY from environment.'
fi

if [ -z "$AK" ]; then
  echo '  ERROR: API Key is required.'
  echo '  Get yours at https://aicraftapi.com/dashboard.html'
  exit 1
fi

# Step 1: Install Claude Code
echo '  [1/2] Installing Claude Code...'
# Try native installer first (recommended by Anthropic)
if command -v curl &> /dev/null; then
  curl -fsSL https://claude.ai/install.sh | bash 2>/dev/null || {
    echo '  Native installer failed, trying npm...'
    npm install -g @anthropic-ai/claude-code
  }
else
  npm install -g @anthropic-ai/claude-code
fi

# Step 2: Write AICraft config
echo '  [2/2] Writing AICraft API config...'
mkdir -p ~/.claude
cat > ~/.claude/settings.json << EOF
{
  "env": {
    "ANTHROPIC_BASE_URL": "https://aicraftapi.com/v1",
    "ANTHROPIC_AUTH_TOKEN": "$AK",
    "ANTHROPIC_MODEL": "auto",
    "ANTHROPIC_DEFAULT_OPUS_MODEL": "auto",
    "ANTHROPIC_DEFAULT_SONNET_MODEL": "auto",
    "ANTHROPIC_DEFAULT_HAIKU_MODEL": "auto",
    "CLAUDE_CODE_SUBAGENT_MODEL": "auto"
  }
}
EOF

echo ''
echo '  Done!'
echo '  Run: claude'
echo ''
echo '  Config: ~/.claude/settings.json'
echo '  Endpoint: https://aicraftapi.com/v1'
echo '  Model: auto (Auto Router enabled)'
echo ''
