#!/usr/bin/env bash
#
# Codu provider auto-setup for OpenCode (Linux/macOS).
#
# Usage:
#   bash install-codu-opencode.sh [sk-ai-...]
#   CODU_API_KEY=sk-ai-... bash install-codu-opencode.sh
#   curl -fsSL https://codu.vu/install-codu-opencode.sh | bash -s -- sk-ai-...
#
# Get an API key at https://codu.vu/panel/keys
set -euo pipefail

KEY="${CODU_API_KEY:-${1:-}}"
if [ -z "$KEY" ]; then
  printf 'Codu API key (sk-ai-...): '
  read -r KEY
fi
if [ -z "$KEY" ]; then
  echo "error: no API key provided" >&2
  exit 1
fi

if ! command -v opencode >/dev/null 2>&1; then
  echo "warning: 'opencode' binary not found in PATH - install it first: https://opencode.ai" >&2
fi

echo "fetching model catalog..."
IDS_FILE=$(mktemp)
OUTIDS=$(mktemp)
trap 'rm -f "$IDS_FILE" "$OUTIDS"' EXIT
if DATA=$(curl -fsSL -m 25 -H "Authorization: Bearer $KEY" https://codu.vu/v1/models 2>/dev/null); then
  set +o pipefail
  printf '%s' "$DATA" \
    | grep -o '"id"[[:space:]]*:[[:space:]]*"[^"]*"' \
    | sed 's/.*"id"[[:space:]]*:[[:space:]]*"//;s/"$//' \
    | grep -v -e '^$' -e '^auto$' -e '^auto/' -e '^ddgw/' -e '^no-think/' \
    | sort -u > "$IDS_FILE"
  set -o pipefail
fi
: > "$OUTIDS"
if [ -s "$IDS_FILE" ]; then
  while IFS= read -r id; do
    base=$(printf '%s' "$id" | sed 's/-\(low\|medium\|high\|xhigh\)$//')
    if [ "$base" = "$id" ] || ! grep -qxF "$base" "$IDS_FILE"; then
      printf '%s\n' "$id" >> "$OUTIDS"
    fi
  done < "$IDS_FILE"
fi
FINAL_IDS=""
if [ -s "$OUTIDS" ]; then
  FINAL_IDS=$(cat "$OUTIDS")
  COUNT=$(printf '%s\n' "$FINAL_IDS" | grep -c .)
  echo "found $COUNT models"
fi
if [ -z "$FINAL_IDS" ]; then
  echo "warning: catalog fetch failed, using starter model set" >&2
  FINAL_IDS="openai/gpt-4o
deepseek/deepseek-chat
cr/claude-opus-5"
fi
if printf '%s\n' "$FINAL_IDS" | grep -qxF "cr/claude-opus-5"; then
  DEFAULT_MODEL="codu/cr/claude-opus-5"
else
  DEFAULT_MODEL="codu/$(printf '%s\n' "$FINAL_IDS" | head -n 1)"
fi
MODELS_BLOCK=$(printf '%s\n' "$FINAL_IDS" | sed 's#.*#        "&": { "name": "&" },#' | sed '$ s/,$//')

CONFIG_DIR="$HOME/.config/opencode"
mkdir -p "$CONFIG_DIR"
CONFIG_FILE="$CONFIG_DIR/opencode.json"
if [ -f "$CONFIG_FILE" ]; then
  cp "$CONFIG_FILE" "$CONFIG_FILE.bak"
  echo "existing config backed up to $CONFIG_FILE.bak"
fi

cat > "$CONFIG_FILE" <<EOF
{
  "\$schema": "https://opencode.ai/config.json",
  "provider": {
    "codu": {
      "npm": "@ai-sdk/openai-compatible",
      "name": "Codu",
      "options": {
        "baseURL": "https://codu.vu/v1",
        "apiKey": "$KEY"
      },
      "models": {
$MODELS_BLOCK
      }
    }
  },
  "model": "$DEFAULT_MODEL"
}
EOF
chmod 600 "$CONFIG_FILE"

echo "Codu provider configured in $CONFIG_FILE"
echo "Next: run 'opencode' and pick a codu/* model with /models"
