#!/usr/bin/env bash
# Registers API credentials into LiteLLM's database so they appear in the web UI.
# Run once after the litellm service is healthy.
# Usage: ./litellm-init-credentials.sh
# Reads credentials from environment (or .env if sourced).

set -euo pipefail

LITELLM_URL="${LITELLM_URL:-http://localhost:18804}"
LITELLM_MASTER_KEY="${LITELLM_MASTER_KEY:?LITELLM_MASTER_KEY is required}"

post_credential() {
  local name="$1"
  local provider="$2"
  local api_key="$3"

  if [ -z "$api_key" ]; then
    echo "  [skip] $name — key is empty"
    return
  fi

  local body="{\"credential_name\":\"$name\",\"credential_values\":{\"api_key\":\"$api_key\"},\"credential_info\":{\"custom_llm_provider\":\"$provider\"}}"

  local status
  status=$(curl -s -o /dev/null -w "%{http_code}" \
    -X POST "$LITELLM_URL/credentials" \
    -H "Authorization: Bearer $LITELLM_MASTER_KEY" \
    -H "Content-Type: application/json" \
    -d "$body")

  if [ "$status" = "200" ] || [ "$status" = "201" ]; then
    echo "  [ok]   $name ($provider)"
  else
    echo "  [fail] $name ($provider) — HTTP $status"
  fi
}

echo "Waiting for LiteLLM to be ready..."
until curl -sf "$LITELLM_URL/health/liveliness" > /dev/null 2>&1; do sleep 2; done
echo "LiteLLM is up. Registering credentials..."

post_credential "anthropic"  "anthropic"  "${ANTHROPIC_API_KEY:-}"
post_credential "openai"     "openai"     "${OPENAI_API_KEY:-}"
post_credential "gemini"     "gemini"     "${GEMINI_API_KEY:-}"
post_credential "zai"        "openai"     "${ZAI_API_KEY:-}"

echo "Registering models..."
sh /litellm-init-models.sh

echo "Done."
