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

TEXT="${1:?Usage: coral_store <text> [metadata_json]}"
METADATA_RAW="${2:-{}}"
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

# Safely JSON-encode the text to handle quotes, newlines, and special characters
ESCAPED_TEXT=$(printf '%s' "$TEXT" | python3 -c 'import json,sys; print(json.dumps(sys.stdin.read()))')

# Validate metadata is valid JSON object; fall back to {} if not (prevents 422)
METADATA=$(printf '%s' "$METADATA_RAW" | python3 -c '
import json,sys
try:
    val=json.load(sys.stdin)
    if isinstance(val,dict):
        print(json.dumps(val))
    else:
        print("{}")
except:
    print("{}")
' 2>/dev/null || echo "{}")

# Memory API — simpler "remember this" interface
RESP=$(curl -s -X POST "${API_URL}/api/v1/memories" \
  -H "Authorization: Bearer ${CORAL_API_KEY}" \
  -H "Content-Type: application/json" \
  -d "{\"text\": ${ESCAPED_TEXT}, \"metadata\": ${METADATA}}")
echo "$RESP" | python3 -c '
import json,sys
raw=sys.stdin.read()
try:
    d=json.loads(raw)
    if "error" in d or "detail" in d:
        print(json.dumps(d))
    else:
        print(json.dumps({"status": d.get("status","success")}))
except Exception:
    print(raw)
' 2>/dev/null || echo "$RESP"
