#!/usr/bin/env bash
# apertus-ask [-m model] [-r] [-s "<system prompt>"] "<question>" — one question to
# Apertus 1.5 70B at Infomaniak THROUGH THE GATE, the reply with its fringe.
#
#   https://bikoret.ch/gate/infomaniak/<product_id>/openai/v1/chat/completions
#
# Keys (read, never printed): the courtyard key — first "courtyard" line of
# ~/.config/shorashim/api_keys; the Infomaniak token and product id — the
# "infomaniak" and "infomaniak_product" lines of ~/.config/shorashim/upstream_keys
# (`upstream-key-set infomaniak`, `upstream-key-set infomaniak_product`).
# -r asks the gate to rebuke once (X-Bikoret-Rebuke: once). BIKORET_URL
# overrides the host. Prints the reply text (fringe included) and, on
# stderr, the verdict header.
set -euo pipefail
MODEL="swiss-ai/Apertus-v1.5-70B"; REBUKE=""; SYSTEM=""
while getopts "m:rs:" o; do case "$o" in m) MODEL="$OPTARG";; r) REBUKE=1;; s) SYSTEM="$OPTARG";; *) exit 2;; esac; done
shift $((OPTIND-1))
[ $# -ge 1 ] || { echo "usage: apertus-ask [-m model] [-r] [-s system] \"<question>\"" >&2; exit 2; }
Q="$*"
BASE="${BIKORET_URL:-https://bikoret.ch}"
CK=$(awk '$1=="courtyard"{print $2; exit}' "$HOME/.config/shorashim/api_keys")
TOKEN=$(awk '$1=="infomaniak"{print $2; exit}' "$HOME/.config/shorashim/upstream_keys")
PRODUCT=$(awk '$1=="infomaniak_product"{print $2; exit}' "$HOME/.config/shorashim/upstream_keys")
[ -n "$CK" ] || { echo "no courtyard key in ~/.config/shorashim/api_keys" >&2; exit 1; }
[ -n "$TOKEN" ] || { echo "no 'infomaniak <token>' line: run upstream-key-set infomaniak" >&2; exit 1; }
case "$PRODUCT" in ""|*[!0-9]*) echo "no numeric 'infomaniak_product <id>' line: run upstream-key-set infomaniak_product" >&2; exit 1;; esac
BODY=$(MODEL="$MODEL" Q="$Q" SYSTEM="$SYSTEM" python3 -I -c '
import json,os
m=[]
if os.environ["SYSTEM"]: m.append({"role":"system","content":os.environ["SYSTEM"]})
m.append({"role":"user","content":os.environ["Q"]})
print(json.dumps({"model":os.environ["MODEL"],"messages":m,"max_tokens":800}))')
HDR=$(mktemp); trap 'rm -f "$HDR"' EXIT
RESP=$(curl -sS -D "$HDR" -X POST "$BASE/gate/infomaniak/$PRODUCT/openai/v1/chat/completions" \
  -H "X-Bikoret-Key: $CK" -H "Authorization: Bearer $TOKEN" \
  ${REBUKE:+-H "X-Bikoret-Rebuke: once"} \
  -H "Content-Type: application/json" --data-binary "$BODY")
grep -i "^x-bikoret-\|^HTTP/" "$HDR" | tr -d '\r' >&2
printf '%s' "$RESP" | python3 -I -c '
import json,sys
r=json.load(sys.stdin)
if "choices" in r: print(r["choices"][0]["message"]["content"])
else: print(json.dumps(r, indent=2, ensure_ascii=False))'
