#!/usr/bin/env bash
set -euo pipefail

QUERY="${1:?Usage: coral_retrieve <query> [k]}"
K="${2:-10}"
API_URL="${CORAL_API_URL:-https://search-api.coralbricks.ai}"

if [ -z "${CORAL_API_KEY:-}" ]; then
  echo '{"error": "CORAL_API_KEY is not set. Get one at https://coralbricks.ai"}' >&2
  exit 1
fi

# Memory API — simpler "recall that" interface
RESP=$(curl -s -X POST "${API_URL}/api/v1/memories/search" \
  -H "Authorization: Bearer ${CORAL_API_KEY}" \
  -H "Content-Type: application/json" \
  -d "{\"query\": $(printf '%s' "$QUERY" | python3 -c 'import json,sys; print(json.dumps(sys.stdin.read()))'), \"k\": ${K}}")
echo "$RESP" | python3 -c '
import json,sys
raw=sys.stdin.read()
try:
    d=json.loads(raw)
    results=d.get("results",[])
    out=[{"text":r.get("text",""),"score":r.get("score",0)} for r in results]
    print(json.dumps({"results":out}))
except: print(raw)
' 2>/dev/null || echo "$RESP"
