#!/bin/bash
# Switch the General RAG agent to the fast, stable model and restart n8n cleanly.
set -uo pipefail
echo "===== stop n8n ====="
docker stop n8n >/dev/null && echo "  stopped"

echo
echo "===== patch workflows ====="
python3 - <<'PY'
import json, sqlite3, shutil, datetime
db='/var/lib/docker/volumes/n8n_n8n_data/_data/database.sqlite'
shutil.copy2(db, db+'.pre-general-'+datetime.datetime.now().strftime('%Y%m%d-%H%M%S'))
c=sqlite3.connect(db)
NEW='gemini/gemini-3.5-flash-lite'
changed=[]
for wid,name,nodes_json in c.execute("select id,name,nodes from workflow_entity").fetchall():
    nodes=json.loads(nodes_json); touched=[]
    for n in nodes:
        if n.get('type','').endswith('lmChatOpenAi') and n.get('name') in ('General Chat Model','General Chat Model1','Intent Chat Model','Intent Chat Model1'):
            p=n.setdefault('parameters',{})
            cur=p.get('model')
            if isinstance(cur,dict):
                if cur.get('value')==NEW: continue
                cur['value']=NEW; cur['cachedResultName']=NEW
            else:
                if cur==NEW: continue
                p['model']=NEW
            touched.append(n.get('name'))
    if touched:
        c.execute("update workflow_entity set nodes=? where id=?", (json.dumps(nodes,ensure_ascii=False), wid))
        changed.append((name, touched))
c.commit()
for name,t in changed: print(f"  {name}: {t}")
print("  (no change)" if not changed else "")
PY

echo
echo "===== start n8n ====="
docker start n8n >/dev/null && echo "  started"
for i in $(seq 1 20); do
  if docker exec n8n wget -q -T 3 -O /dev/null http://127.0.0.1:5678/healthz 2>/dev/null; then echo "  healthy"; break; fi
  sleep 3
done

echo
echo "===== final models in active workflow ====="
python3 - <<'PY'
import json, sqlite3
c=sqlite3.connect('/var/lib/docker/volumes/n8n_n8n_data/_data/database.sqlite')
for name,nodes_json in c.execute("select name,nodes from workflow_entity where active=1"):
    for n in json.loads(nodes_json):
        if n.get('type','').endswith('lmChatOpenAi'):
            m=n.get('parameters',{}).get('model')
            m=m.get('value') if isinstance(m,dict) else m
            print(f"  {n.get('name'):28s} -> {m}")
PY

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