#!/usr/bin/env bash
# create-llm-proxy-with-budget.sh — register an OpenAI proxy with an allowed
# model whitelist and a monthly hard budget cap, then mint a scoped client key.
#
# Usage:
#   AIRONCLAW_TOKEN=... ./create-llm-proxy-with-budget.sh <name> <openai-key>

set -euo pipefail

NAME="${1:?usage: create-llm-proxy-with-budget.sh <name> <openai-key>}"
PROVIDER_KEY="${2:?usage: create-llm-proxy-with-budget.sh <name> <openai-key>}"

BASE="${AIRONCLAW_BASE_URL:-https://dashboard.aironclaw.com}"
TOKEN="${AIRONCLAW_TOKEN:?AIRONCLAW_TOKEN must be set}"

# 1. Create the proxy with a $500/month hard cap
echo ">>> creating LLM proxy '$NAME'"
BODY=$(jq -nc \
  --arg name "$NAME" --arg key "$PROVIDER_KEY" \
  '{
    name: $name,
    provider: "openai",
    allowedModels: ["gpt-4o-mini", "gpt-4o"],
    defaultModel: "gpt-4o-mini",
    providerKey: $key,
    logConversations: false,
    budget: { period: "monthly", capUsd: 500, hardBlock: true }
  }')

PROXY=$(curl -fsS -X POST \
  -H "Authorization: Bearer ${TOKEN}" \
  -H "Content-Type: application/json" \
  "${BASE}/api/llm" -d "$BODY")
LLM_ID=$(echo "$PROXY" | jq -r '.proxy.id')
PROXY_HOST=$(echo "$PROXY" | jq -r '.proxy.proxyHost')
echo "    id:         $LLM_ID"
echo "    proxy host: $PROXY_HOST"

# 2. Mint a key scoped to gpt-4o-mini only
echo ">>> minting a client key (gpt-4o-mini only)"
KEY_BODY=$(jq -nc --arg n "${NAME}-mini" --arg id "$LLM_ID" \
  '{name:$n, llmPermissions:[{id:$id, models:["gpt-4o-mini"]}]}')
KEY=$(curl -fsS -X POST \
  -H "Authorization: Bearer ${TOKEN}" \
  -H "Content-Type: application/json" \
  "${BASE}/api/keys" -d "$KEY_BODY")
PLAINTEXT=$(echo "$KEY" | jq -r '.key.key')

cat <<EOF

Done.

Clients can now call OpenAI through AIronClaw at:
  https://${PROXY_HOST}/v1/chat/completions

with header:
  Authorization: Bearer ${PLAINTEXT}

The proxy will:
  - reject any model other than gpt-4o-mini or gpt-4o
  - count tokens, compute cost, enforce a \$500/month hard cap
  - return HTTP 402 once the cap is exceeded (until the 1st of next month)

To see live spend:
  curl -fsS -H "Authorization: Bearer \${AIRONCLAW_TOKEN}" \\
    "${BASE}/api/llm/${LLM_ID}/usage/daily?days=14" | jq .window
EOF
