#!/bin/bash
export LC_ALL=C
cd /root/n8n || exit 1
cp -a docker-compose.yml "/root/n8n/docker-compose.yml.bak-singlenet-$(date +%Y%m%d-%H%M%S)"

python3 - <<'PY'
p='/root/n8n/docker-compose.yml'
src=open(p).read()
old="""    networks:
      - default
      - esaricity"""
new="""    networks:
      - default"""
if old not in src:
    print("  networks block already changed"); raise SystemExit(0)
open(p,'w').write(src.replace(old,new))
print("  n8n now attaches only the default (n8n_default) network")
PY

echo
echo "===== RECREATE ====="
docker compose up -d --force-recreate n8n 2>&1 | tail -3
for i in $(seq 1 25); do
  docker exec n8n wget -q -T 3 -O /dev/null http://127.0.0.1:5678/healthz 2>/dev/null && { echo "  healthz OK"; break; }
  sleep 3
done

echo
echo "  networks: $(docker inspect n8n --format '{{range $k,$v := .NetworkSettings.Networks}}{{$k}}={{$v.IPAddress}} {{end}}')"

echo
echo "===== ALL THREE SERVICE PATHS FROM n8n ====="
docker exec n8n node -e '
(async()=>{for(const [h,p,path] of [["9router",20128,"/api/health"],["qdrant",6333,"/collections"],["ollama",11434,"/api/version"],["172.19.0.1",20808,""]]){
  const t=Date.now();
  try{const r=await fetch(`http://${h}:${p}${path}`,{signal:AbortSignal.timeout(7000)});
    console.log(`  ${h}:${p}${path||"/"} -> ${r.status} ${Date.now()-t}ms`);
  }catch(e){console.log(`  ${h}:${p} -> FAIL ${e.cause?.code||e.message}`)}
}})();' 2>&1 | head -6

echo
echo "===== RAG PATH AGAIN ====="
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 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:false})});
 const sj=await sr.json();
 console.log(`  embed+search -> ${sr.status} hits=${(sj.result||[]).length} total=${Date.now()-t0}ms`);
})().catch(e=>console.log("  FAIL",e.cause?.code||e.message));' 2>&1 | head -3

echo
echo "  version: $(docker exec n8n n8n --version 2>/dev/null | tail -1)"
