#!/usr/bin/env bash
set -euo pipefail
cd "$(dirname "$0")"
[[ -f .env ]] || { echo "Missing .env; run setup-clearai.sh" >&2; exit 1; }
DOMAIN="$(sed -n 's/^GATEWAY_DOMAIN=//p' .env | head -1)"
[[ -n "$DOMAIN" ]] || { echo "Missing domain in .env" >&2; exit 1; }
read -r -s -p "Paste FreeLLMAPI unified API key (not your upstream key): " KEY
printf '\n'
[[ -n "$KEY" ]] || { echo "Missing key" >&2; exit 1; }
trap 'unset KEY' EXIT
printf 'Checking model API on %s\n' "$DOMAIN"
# This verifies public HTTPS and an authenticated models response, not inference.
curl --fail-with-body --proto '=https' --tlsv1.2 -sS --show-error \
  --max-time 20 -H "Authorization: Bearer $KEY" \
  "https://$DOMAIN/v1/models?available=true" \
  | python3 -c 'import json,sys
r=json.load(sys.stdin)
a=r.get("data",[])
if not isinstance(a,list):
    print("Unexpected /v1/models response");sys.exit(1)
print(f"Authenticated models request succeeded; available model entries: {len(a)}")
for m in a[:12]:
    if isinstance(m,dict): print(" -",m.get("id","(missing ID)"))
if not a: print("No available models yet; add an enabled upstream provider key in the private dashboard.")' 
printf '\n\nTo test chat inference, send a message from ClearAI Settings (model: auto).\n'
