#!/usr/bin/env bash
# Fronset cookbook 5: your own keys, how comparison runs, and how to switch it
# off, in curl. The same steps as cb5_your_own_keys.py, for one task. Needs curl
# and jq.
#
#   export FRONSET_INFERENCE_KEY=llmb_i_...  FRONSET_MANAGEMENT_KEY=llmb_m_...
#   export PROVIDER_SLUG=openai PROVIDER_API_KEY=sk-...   # optional, step 1
#   export COMPARISON=off                                 # on (default) or off
#   export CALLS=10                                       # calls in the run
#   bash cb5_your_own_keys.sh
set -euo pipefail
API="${FRONSET_API_BASE:-https://api.fronset.ai}"
COMPARISON="${COMPARISON:-on}"
CALLS="${CALLS:-10}"
TASK="${TASK:-cookbook-5-$(date -u +%Y%m%d)-$COMPARISON}"
M="Authorization: Bearer $FRONSET_MANAGEMENT_KEY"

# Step 1. Vault one provider key (management key), then read the vault back.
# The read returns metadata and the key's last four characters, never the key.
if [ -n "${PROVIDER_API_KEY:-}" ]; then
  jq -n --arg k "$PROVIDER_API_KEY" '{api_key: $k, config: {}}' |
  curl -sS -X PUT "$API/api/inference/v1/vault/providers/$PROVIDER_SLUG" \
    -H "$M" -H "Content-Type: application/json" --data @- | jq '{provider_slug, verified}'
fi
curl -sS "$API/api/inference/v1/vault/providers" -H "$M" |
  jq '[.[] | {provider_slug, is_active, key_hint, verified}]'

# Step 2. Create the task, or reuse it if it exists and is active.
PREFIX=$(curl -sS "$API/api/inference/v1/management/account" -H "$M" | jq -r .task_prefix)
CODE=$(curl -sS "$API/api/inference/v1/management/capabilities/$PREFIX$TASK" \
  -H "$M" -o cap.json -w '%{http_code}')
if [ "$CODE" = 404 ]; then
  jq -n --arg n "$TASK" --arg g "${TASK:0:41}-models" '{slug: $n,
      display_name: "Cookbook 5: sort a support ticket",
      description: "Sort a support ticket into one of five categories.",
      pricing_mode: "byok",
      templates: [{key: "default",
        system: "You sort customer support tickets. Answer with the one category that fits best: billing, delivery, defect, account, other.",
        user: "Ticket: {ticket}",
        variables: [{name: "ticket", required: true, description: "The ticket text."}]}],
      output_format: "json_schema",
      output_schema: {type: "object",
        properties: {category: {type: "string",
          enum: ["billing", "delivery", "defect", "account", "other"]}},
        required: ["category"], additionalProperties: false},
      model_group: {name: $g, models: ["gpt-5.4-nano", "gpt-6-luna"]}}' |
  curl -sS -X POST "$API/api/inference/v1/management/capabilities/" \
    -H "$M" -H "Content-Type: application/json" --data @- -o cap.json
  jq '{slug, exploration: (.exploration | {status, fans_out, judging})}' cap.json
fi
SLUG=$(jq -r .slug cap.json)

# Step 3 or 4. The calls, on the native endpoint. With comparison off, each call
# carries "selection": {"fan_out_strategy": "never"}.
SEL='{}'; [ "$COMPARISON" = off ] && SEL='{"selection": {"fan_out_strategy": "never"}}'
for i in $(seq 1 "$CALLS"); do
  jq -n --arg s "$SLUG" --arg w "cookbook-5-$COMPARISON" \
        --arg t "Ticket $i: the parcel with my Brook kettle was left at the wrong address." \
        --argjson sel "$SEL" \
     '{capability_slug: $s, workflow_id: $w, prompt_vars: {ticket: $t}} + $sel' |
  curl -sS -X POST "$API/api/inference/v1/invocations/" --max-time 900 --keepalive-time 30 \
    -H "Authorization: Bearer $FRONSET_INFERENCE_KEY" -H "Content-Type: application/json" \
    --data @- |
  jq -c '{status, model_id, cost_usd, compared: (.panel_version != null),
          error_code, error_message}'
done

