#!/bin/bash
# Get stack trace of hot thread
PID=$(pgrep -f 'python main.py' | head -1)
if [ -z "$PID" ]; then echo "NO PROCESS"; exit 1; fi

echo "=== Hot thread CPU ==="
HOT_TID=$(ps -p $PID -L -o tid,pcpu --no-header | sort -k2 -rn | head -1 | awk '{print $1}')
echo "Hot thread: $HOT_TID"
ps -p $PID -L -o tid,pcpu,state --no-header | sort -k2 -rn | head -5

echo ""
echo "=== Hot thread kernel stack ==="
cat /proc/$PID/task/$HOT_TID/stack 2>/dev/null || echo "Need root for kernel stack"

echo ""
echo "=== Python faulthandler dump ==="
# Send SIGUSR1 to trigger faulthandler if it's enabled
kill -USR1 $PID 2>/dev/null
sleep 2
tail -50 /home/fabian/comfyui7.log | head -30

echo ""
echo "=== Try py-spy ==="
which py-spy 2>/dev/null && timeout 3 py-spy dump --pid $PID 2>&1 | head -40 || echo "No py-spy"

echo ""
echo "=== /proc/$PID/syscall ==="
cat /proc/$PID/task/$HOT_TID/syscall 2>/dev/null | head -1
