#!/bin/bash
pid=$(pgrep -f "python.*main.py" | head -1)
echo "PID: $pid"
if [ -z "$pid" ]; then
    echo "NO COMFYUI PROCESS"
    echo "=== Last 30 lines of log ==="
    tail -30 /home/fabian/comfyui8.log 2>/dev/null
    echo "=== Output files ==="
    ls -la /home/fabian/ComfyUI/output/ 2>/dev/null
    exit 0
fi

rss=$(cat /proc/$pid/status 2>/dev/null | grep VmRSS | awk '{print $2}')
swap=$(cat /proc/$pid/status 2>/dev/null | grep VmSwap | awk '{print $2}')
echo "RSS: ${rss}kB  Swap: ${swap}kB"

echo "=== Active threads ==="
for tid in $(ls /proc/$pid/task/ 2>/dev/null); do
    state=$(cat /proc/$pid/task/$tid/stat 2>/dev/null | awk '{print $3}')
    if [ "$state" = "R" ]; then
        ticks=$(cat /proc/$pid/task/$tid/stat 2>/dev/null | awk '{print $14+$15}')
        echo "  RUNNING TID $tid ticks=$ticks"
    fi
done

echo "=== Last 30 log ==="
tail -30 /home/fabian/comfyui8.log 2>/dev/null

echo "=== Output files ==="
ls -la /home/fabian/ComfyUI/output/ 2>/dev/null

echo ""
echo "=== py-spy ==="
echo 0 | sudo tee /proc/sys/kernel/yama/ptrace_scope > /dev/null 2>&1
/home/fabian/ComfyUI/venv/bin/py-spy dump --pid $pid 2>&1 | head -40
