#!/usr/bin/env bash
set -euo pipefail
: "${LAB0_API_KEY:?Set LAB0_API_KEY to a Read & write key}"
base="${LAB0_BASE_URL:-https://app.lab0.ai/app}"
base="${base%/}"
namespace="${LAB0_NAMESPACE:-quickstart}"
file="${LAB0_FILE_PATH:-plan.md}"

request() {
  curl --fail-with-body --silent --show-error --max-time 200 \
    --header "Authorization: Bearer $LAB0_API_KEY" "$@"
}

uploaded="$(request --form "file=@$file" --form "namespace=$namespace" \
  "$base/api/knowledge/files")"
file_id="$(printf '%s' "$uploaded" | jq -er '.id')"
ready=false
for ((attempt = 0; attempt < 90; attempt++)); do
  document="$(request "$base/api/knowledge/files/$file_id")"
  status="$(printf '%s' "$document" | jq -r '.status')"
  if [[ "$status" == ready ]]; then ready=true; break; fi
  if [[ "$status" == failed ]]; then
    printf '%s' "$document" | jq -r '.error' >&2
    exit 1
  fi
  sleep 2
done
if [[ "$ready" != true ]]; then
  echo "Processing timed out; inspect file $file_id before trying again." >&2
  exit 1
fi
body="$(jq -n --arg namespace "$namespace" --arg file "$file_id" \
  '{prompt:"How is the rollout run?",namespace:$namespace,file_ids:[$file]}')"
request --header 'Content-Type: application/json' --data "$body" \
  "$base/api/knowledge/respond" | jq .
