#!/bin/bash
export LC_ALL=C
echo "===== END-TO-END RAG PATH FROM n8n (embed -> search) ====="
docker exec n8n node -e '
(async()=>{
  const t0=Date.now();
  const er=await fetch("http://ollama:11434/api/embeddings",{method:"POST",headers:{"Content-Type":"application/json"},
    body:JSON.stringify({model:"bge-m3:latest",prompt:"شهرداری ساری کجاست؟"})});
  const ej=await er.json(); const t1=Date.now();
  console.log(`  embed  : ${er.status} dim=${ej.embedding?.length} ${t1-t0}ms`);
  const sr=await fetch("http://qdrant:6333/collections/SariKnowledgeV2/points/search",{method:"POST",
    headers:{"Content-Type":"application/json"},
    body:JSON.stringify({vector:ej.embedding,limit:3,with_payload:true})});
  const sj=await sr.json(); const t2=Date.now();
  const hits=(sj.result||[]).length;
  console.log(`  search : ${sr.status} hits=${hits} ${t2-t1}ms`);
  if(hits) console.log(`  top    : score=${(sj.result[0].score||0).toFixed(3)} :: ${String(sj.result[0].payload?.pageContent||"").slice(0,80)}`);
  console.log(`  TOTAL  : ${t2-t0}ms`);
})().catch(e=>console.log("  FAIL",e.cause?.code||e.message));' 2>&1 | head -8

echo
echo "===== RECREATE VIA COMPOSE (verify the network fix sticks) ====="
cd /root/n8n && docker compose up -d n8n 2>&1 | tail -3
for i in $(seq 1 20); do
  docker exec n8n wget -q -T 3 -O /dev/null http://127.0.0.1:5678/healthz 2>/dev/null && break
  sleep 3
done
echo "  networks after recreate:"
docker inspect n8n --format '{{range $k,$v := .NetworkSettings.Networks}}    {{$k}} {{$v.IPAddress}}{{println}}{{end}}'

echo
echo "===== RE-TEST AFTER RECREATE ====="
docker exec n8n node -e '
(async()=>{for(const [h,p,path] of [["qdrant",6333,"/collections"],["ollama",11434,"/api/version"]]){
  const t=Date.now();try{const r=await fetch(`http://${h}:${p}${path}`,{signal:AbortSignal.timeout(6000)});
  console.log(`  ${h} -> ${r.status} ${Date.now()-t}ms`)}catch(e){console.log(`  ${h} -> FAIL ${e.cause?.code}`)}}})();' 2>&1 | head -3

echo
echo "===== FINAL STATE ====="
docker ps --filter name=n8n --format '  {{.Status}}'
docker exec n8n n8n --version 2>/dev/null | tail -1
