#!/bin/bash
A=$(cat "$1/token.txt")
ask() {
  cid=$(curl -s -X POST "https://pedshub.com/api/ai/conversations" -H "Authorization: Bearer $A" \
        -H "Content-Type: application/json" -d '{}' | python3 -c "import json,sys;print(json.load(sys.stdin).get('id',''))")
  [ -z "$cid" ] && { echo "  (could not open a thread)"; return; }
  curl -s -X POST "https://pedshub.com/api/ai/conversations/$cid/messages" -H "Authorization: Bearer $A" \
    -H "Content-Type: application/json" -d "$(python3 -c "import json,sys;print(json.dumps({'message':sys.argv[1]}))" "$2")" \
  | python3 -c "
import json,sys
d=json.load(sys.stdin)
m=d.get('message') or {}
text=' '.join((m.get('content') or '').split())
cites=len(m.get('citations') or [])
print(f'  [{cites} cites] {text[:300]}')
"
}
while IFS= read -r q; do
  [ -z "$q" ] && continue
  echo "Q: $q"
  ask "$1" "$q"
  echo
done
