#!/bin/bash
export LC_ALL=C
DB=/var/lib/docker/volumes/n8n_n8n_data/_data/database.sqlite
cp "$DB" /tmp/n8n_exec.db 2>/dev/null

echo "===== LAST 8 EXECUTIONS ====="
python3 - <<'PY'
import sqlite3, json, datetime
c=sqlite3.connect('/tmp/n8n_exec.db'); c.row_factory=sqlite3.Row
cols=[r[1] for r in c.execute("pragma table_info(execution_entity)")]
print("  cols:", cols)
rows=c.execute("select * from execution_entity order by id desc limit 8").fetchall()
for r in rows:
    d=dict(r)
    print(f"  id={d.get('id')} status={d.get('status')} mode={d.get('mode')} started={d.get('startedAt')} stopped={d.get('stoppedAt')} wf={d.get('workflowId')}")
PY

echo
echo "===== ERROR DETAIL OF LAST 2 FAILED ====="
python3 - <<'PY'
import sqlite3, json
c=sqlite3.connect('/tmp/n8n_exec.db'); c.row_factory=sqlite3.Row
rows=c.execute("select * from execution_entity where status='error' order by id desc limit 2").fetchall()
if not rows:
    print("  no failed executions found")
for r in rows:
    d=dict(r)
    print(f"\n--- execution {d['id']} ({d.get('startedAt')}) workflow {d.get('workflowId')}")
    raw=d.get('data')
    if not raw:
        print("  no data"); continue
    try:
        data=json.loads(raw)
    except Exception as e:
        print("  parse error", e); continue
    rd=data.get('resultData',{})
    err=rd.get('error') or data.get('error')
    if err:
        print("  node:", err.get('node',{}).get('name') if isinstance(err.get('node'),dict) else err.get('node'))
        print("  message:", str(err.get('message'))[:300])
        print("  description:", str(err.get('description'))[:300])
        print("  stack:", str(err.get('stack'))[:400].replace('\n',' | '))
    # last node executed
    run=rd.get('runData',{})
    order=list(run.keys())
    print("  nodes run:", order[-4:])
    for n in order[-3:]:
        try:
            item=run[n][0]
            e=item.get('error')
            if e:
                print(f"    [{n}] error:", str(e.get('message'))[:200])
        except Exception: pass
PY

echo
echo "===== OLLAMA CONTAINER STATE ====="
docker ps -a --filter name=ollama --format '  {{.Names}} | {{.Status}}'
docker inspect ollama --format '  restarts={{.RestartCount}} oom={{.State.OOMKilled}} exit={{.State.ExitCode}}' 2>/dev/null

echo
echo "===== OLLAMA LOG (last errors) ====="
docker logs ollama --since 3h 2>&1 | tail -15
