#!/usr/bin/env bash
# Requires bash, curl, jq, S1M_API_KEY and TENSORX_API_KEY.
set -euo pipefail
: "${S1M_API_KEY:?Set S1M_API_KEY}" "${TENSORX_API_KEY:?Set TENSORX_API_KEY}"
request='Write a Python function that returns the square of a number.'
fast='deepseek/deepseek-v3.2'
strong='deepseek/deepseek-v4.1-flash'
# Edit this category x difficulty table and fallback for your own catalog.
routes=$(jq -n --arg fast "$fast" --arg strong "$strong"   '{coding:{easy:$fast,hard:$strong},general:{easy:$fast,hard:$strong}}')
classifier_payload=$(jq --arg request "$request" '.state.request = $request' <<'CLASSIFIER_JSON'
{"model":"s1-llm-auto-router","state":{"request":"Write a Python function that returns the square of a number.","context":"(new conversation)"},"questions":{"category":{"type":"choice","criteria":{"coding":"","agentic":"","math":"","knowledge":"","long_context":"","tool_use":"","design":"","summarisation":"","general":""}},"difficulty":{"type":"score","criteria":["trivial","easy","moderate","hard","frontier"]},"stakes":{"type":"score","criteria":["negligible","low","medium","high"]},"needs_tools":{"type":"noul"},"needs_vision":{"type":"noul"},"needs_long_context":{"type":"noul"},"follow_up":{"type":"noul"}}}
CLASSIFIER_JSON
)
result=$(curl --fail-with-body --silent --show-error --max-time 60 \
  https://api.system1models.ai/v1/systemone \
  -H "Authorization: Bearer $S1M_API_KEY" -H 'Content-Type: application/json' \
  --data-binary "$classifier_payload")
decision=$(jq --argjson routes "$routes" --arg fallback "$strong" '
  .answers as $a | (if $a.difficulty.score >= 2 then "hard" else "easy" end) as $level |
  ([$a | to_entries[] | select(.key == "needs_tools" or .key == "needs_vision" or
     .key == "needs_long_context" or .key == "follow_up") | select(.value.noul >= 0.5) | .key]) as $unsupported |
  {request_id:.id, signals:$a, unsupported:$unsupported,
   model:(if $a.category.confidence < 0.6 or $a.stakes.score >= 2 then $fallback
          else ($routes[$a.category.choice][$level] // $fallback) end),
   reason:(if $a.category.confidence < 0.6 or $a.stakes.score >= 2 then
           "low confidence or high stakes" else "category/difficulty table" end)}' <<<"$result")
printf '%s\n' "$decision"  # distributions + flag probabilities; no prompts/keys
if [ "$(jq '.unsupported | length' <<<"$decision")" != 0 ]; then
  echo 'Configure capability support / conversation history before forwarding' >&2; exit 1
fi
model=$(jq -r '.model' <<<"$decision")
payload=$(jq -n --arg model "$model" --arg request "$request"   '{model:$model,messages:[{role:"user",content:$request}],max_tokens:80,temperature:0}')
curl --fail-with-body --silent --show-error --max-time 60   https://api.tensorx.ai/v1/chat/completions   -H "Authorization: Bearer $TENSORX_API_KEY" -H 'Content-Type: application/json'   --data-binary "$payload" | jq -r '.choices[0].message.content'
