#!/usr/bin/env bash
# Phase 1 verification: run after re-indexing a pilot repo.
set -euo pipefail

RAG_URL="${RAG_URL:-http://localhost:6005/api/v1}"
REPO_ID="${REPO_ID:?Set REPO_ID to a re-indexed pilot repository}"
QUESTION="${QUESTION:-What are the main features and functionality of this repository?}"

echo "== Search =="
SEARCH_JSON=$(curl -sf -X POST "${RAG_URL}/search" \
  -H 'Content-Type: application/json' \
  -d "{\"repo_id\":\"${REPO_ID}\",\"question\":\"${QUESTION}\"}")

echo "${SEARCH_JSON}" | python3 - <<'PY'
import json, sys
body = json.load(sys.stdin)
meta = body.get("metadata") or {}
hits = body.get("hits") or []
docs = body.get("doc_excerpts") or []
print(f"retrieval_count={meta.get('retrieval_count')}")
print(f"top_retrieval_score={meta.get('top_retrieval_score')}")
print(f"retrieval_fallback_used={meta.get('retrieval_fallback_used')}")
print(f"doc_excerpts={len(docs)} hits={len(hits)}")
if meta.get("retrieval_count", 0) == 0:
    raise SystemExit("FAIL: no retrieval hits")
if (meta.get("top_retrieval_score") or 0) < 0.15:
    raise SystemExit("FAIL: top_retrieval_score below 0.15")
print("PASS: search returned useful retrieval context")
PY

echo
echo "== Query =="
QUERY_JSON=$(curl -sf -X POST "${RAG_URL}/query" \
  -H 'Content-Type: application/json' \
  -d "{\"repo_id\":\"${REPO_ID}\",\"question\":\"${QUESTION}\",\"options\":{\"stream\":false}}")

echo "${QUERY_JSON}" | python3 - <<'PY'
import json, sys
body = json.load(sys.stdin)
answer = (body.get("answer") or "").lower()
meta = body.get("metadata") or {}
if "could not find relevant indexed context" in answer:
    raise SystemExit("FAIL: query returned NO_CONTEXT_ANSWER")
if meta.get("retrieval_count", 0) == 0:
    raise SystemExit("FAIL: query metadata retrieval_count is 0")
print(f"retrieval_count={meta.get('retrieval_count')}")
print(f"top_retrieval_score={meta.get('top_retrieval_score')}")
print("PASS: query produced a contextual answer")
PY

echo
echo "All Phase 1 checks passed for repo ${REPO_ID}"
