#!/usr/bin/env bash
# T-01 "Build a support assistant" — the assembled driver.
# Runs every checkpoint end to end against the local stack.
# Usage:  source /tmp/inaya_env.sh && export INAYA_LABS_ENVIRONMENT=local
#         bash docs-src/tutorials/_code/support-assistant/support_assistant.sh
set -euo pipefail

# ── configuration ────────────────────────────────────────────────────────────
: "${INAYA_LABS_API_KEY:?set INAYA_LABS_API_KEY (source /tmp/inaya_env.sh)}"
: "${INAYA_LABS_APP_KEY:?set INAYA_LABS_APP_KEY}"
INAYA_API_KEY="${INAYA_LABS_API_KEY}"
INAYA_APP_KEY="${INAYA_LABS_APP_KEY}"
TENANT_ID="${TENANT_ID:-playground_a43b973c77e94b7f8b0e64d96c86edf8}"
AUTH_URL="${AUTH_URL:-http://127.0.0.1:40004}"
RAG_URL="${RAG_URL:-http://127.0.0.1:40100}"
EVG_URL="${EVG_URL:-http://127.0.0.1:40071}"
NOTIF_URL="${NOTIF_URL:-http://127.0.0.1:40013}"
NOTIF_PRIV_URL="${NOTIF_PRIV_URL:-http://127.0.0.1:40014}"
COLLECTION="support_faq"
HERE="$(cd "$(dirname "$0")" && pwd)"

echo "═══ T-01 support assistant · tenant ${TENANT_ID} ═══"

# ── checkpoint 1: authenticate ───────────────────────────────────────────────
TOKEN=$(curl -sf -X POST "${AUTH_URL}/v3/auth/qa/login" \
  -H "Content-Type: application/json" \
  -H "x-api-key: ${INAYA_API_KEY}" -H "x-client-app-key: ${INAYA_APP_KEY}" \
  -d "{\"device_id\": \"acme-support-01\", \"locale\": \"en-US\", \"tenant_id\": \"${TENANT_ID}\", \"username\": \"acme-support-bot\"}" \
  | python3 -c 'import json,sys; print(json.load(sys.stdin)["token"])')
AUTH=(-H "Authorization: Bearer ${TOKEN}" -H "x-api-key: ${INAYA_API_KEY}" -H "x-client-app-key: ${INAYA_APP_KEY}")
echo "✔ checkpoint 1 — authenticated"

# ── checkpoint 2: ingest the FAQ ─────────────────────────────────────────────
DOC_ID=$(curl -sf -X POST "${RAG_URL}/v3/ingest?collection_id=${COLLECTION}" \
  "${AUTH[@]}" -H "X-File-Name: faq.txt" -H "Content-Type: application/octet-stream" \
  --data-binary @"${HERE}/faq.txt" \
  | python3 -c 'import json,sys; print(json.load(sys.stdin)["document_id"])')
echo "✔ checkpoint 2 — FAQ ingested as ${DOC_ID}"

# ── checkpoint 3: grounded chat ──────────────────────────────────────────────
SESSION_ID=$(curl -s -X POST "${EVG_URL}/v3/sessions" "${AUTH[@]}" \
  -H "Content-Type: application/json" \
  -d '{
    "required_modalities": ["Text"],
    "selection_criteria": [ { "Model": { "optionality": "MustHave", "name": "Qwen3_VL_4B_Q4" } } ],
    "system_prompt": "You are the Acme Homeware support assistant. Answer only from the provided FAQ context, in one short sentence.",
    "temperature": 0.2,
    "use_rag": { "collection_id": "'"${COLLECTION}"'", "include_glossary": true }
  }' | python3 -c 'import json,sys; print(json.load(sys.stdin)["ai_session_id"])')
echo "   session ${SESSION_ID} (first reply pays model-load cost)…"
curl -s -X POST "${EVG_URL}/v3/sessions/${SESSION_ID}/chat-messages" "${AUTH[@]}" \
  -F "user_message=How long do I have to return an item for a full refund?" \
  | python3 -c 'import json,sys; m=json.load(sys.stdin); print("✔ checkpoint 3 —", " ".join(c["Text"] for c in m["content"] if "Text" in c))'

# ── checkpoint 4: escalation over notifications ─────────────────────────────
SSE_FILE=$(mktemp /tmp/t01-escalation.XXXXXX)
curl -s -N -X POST "${NOTIF_URL}/v3/notifications/subscribe/multi" "${AUTH[@]}" \
  -H "Content-Type: application/json" \
  -d "{\"tenant_id\": \"${TENANT_ID}\", \"subscriptions\": [{\"topic\": \"support-escalations\"}]}" \
  > "${SSE_FILE}" 2>&1 &
SSE_PID=$!
sleep 3
QUESTION="I have asked twice already — escalate this to a manager."
if echo "${QUESTION}" | grep -qiE "escalate|manager"; then
  curl -sf -X POST "${NOTIF_PRIV_URL}/v3/notifications/publish" "${AUTH[@]}" \
    -H "Content-Type: application/json" \
    -d "{\"tenant_id\": \"${TENANT_ID}\", \"topic\": \"support-escalations\", \"sub_topic\": \"ticket-4711\", \"payload\": \"{\\\"question\\\": \\\"${QUESTION}\\\"}\"}" \
    > /dev/null
fi
sleep 3
grep -q "support-escalations" "${SSE_FILE}" && echo "✔ checkpoint 4 — dashboard received the escalation"
kill "${SSE_PID}" 2>/dev/null || true

# ── checkpoint 5: failure injection (RAG down → recover) ─────────────────────
pkill -x rag-service && echo "   rag-service killed; search should now fail visibly"
sleep 1
if curl -s -o /dev/null -m 5 "${RAG_URL}/v3/search" "${AUTH[@]}" \
     -H "Content-Type: application/json" \
     -d "{\"collection_id\": \"${COLLECTION}\", \"question\": \"refund window?\"}"; then
  echo "unexpected: search succeeded while RAG was down"; exit 1
else
  echo "✔ checkpoint 5a — failure is visible (connection refused)"
fi
source /tmp/inaya_env.sh
export INAYA_LABS_ENVIRONMENT=local
nohup "$(cd "${HERE}/../../../../.." && pwd)/target/debug/rag-service" > /tmp/rag-service.log 2>&1 &
for i in $(seq 1 20); do
  CODE=$(curl -s -m 2 -o /dev/null -w "%{http_code}" "${RAG_URL}/v3/health" || echo 000)
  [ "${CODE}" = "200" ] && break
  sleep 2
done
[ "${CODE}" = "200" ] || { echo "rag-service did not recover"; exit 1; }
curl -sf -X POST "${RAG_URL}/v3/search" "${AUTH[@]}" \
  -H "Content-Type: application/json" \
  -d "{\"collection_id\": \"${COLLECTION}\", \"question\": \"How long do I have to return an item?\"}" \
  | python3 -c 'import json,sys; d=json.load(sys.stdin); assert d["chunks"]; print("✔ checkpoint 5b — corpus intact after recovery")'

echo "═══ T-01 complete ═══"
echo "cleanup: DELETE ${EVG_URL}/v3/sessions/${SESSION_ID} and ${RAG_URL}/v3/documents/${DOC_ID}"
