#!/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 "===== TABLES ====="
python3 -c "
import sqlite3
c=sqlite3.connect('/tmp/n8n_exec.db')
print(' ', [r[0] for r in c.execute(\"select name from sqlite_master where type='table'\")])"

echo
echo "===== LATEST EXECUTIONS (now) ====="
python3 - <<'PY'
import sqlite3
c=sqlite3.connect('/tmp/n8n_exec.db')
for r in c.execute("select id,status,mode,startedAt,stoppedAt,jsonSizeBytes from execution_entity order by id desc limit 6"):
    print("  id=%s status=%s mode=%s start=%s stop=%s size=%s" % r)
PY

echo
echo "===== ERROR PAYLOAD FROM execution_data ====="
python3 - <<'PY'
import sqlite3, json
c=sqlite3.connect('/tmp/n8n_exec.db')
try:
    cols=[r[1] for r in c.execute("pragma table_info(execution_data)")]
    print("  execution_data cols:", cols)
except Exception as e:
    print("  no execution_data:", e); raise SystemExit

rows=c.execute("""
  select e.id, e.status, e.startedAt, d.data
  from execution_entity e left join execution_data d on d.executionId=e.id
  where e.status='error' order by e.id desc limit 2""").fetchall()
for eid, status, started, raw in rows:
    print(f"\n--- execution {eid} ({started})")
    if not raw:
        print("   (no data row)"); continue
    try:
        data=json.loads(raw)
    except Exception as exc:
        print("   parse err", exc); continue
    rd=data.get('resultData',{})
    err=rd.get('error') or {}
    node=err.get('node')
    node = node.get('name') if isinstance(node,dict) else node
    print("   failing node:", node)
    print("   message     :", str(err.get('message'))[:250])
    print("   description :", str(err.get('description'))[:250])
    ctx=(err.get('context') or {})
    if ctx: print("   context     :", str(ctx)[:250])
    print("   lastError   :", str(err.get('lastNodeExecuted'))[:120])
    for n, r in list((rd.get('runData') or {}).items())[-3:]:
        try:
            e=(r[0] or {}).get('error')
            if e: print(f"   [{n}] ->", str(e.get('message'))[:200])
        except Exception: pass
PY
