#!/bin/bash
# Diagnose → Kill → Fix
set -e

echo "=== DIAG ==="
PID=$(pgrep -f "python main.py" || true)
if [ -n "$PID" ]; then
    echo "PID: $PID"
    cat /proc/$PID/status 2>/dev/null | grep -E 'State|Threads|VmRSS' || true
    cat /proc/$PID/wchan 2>/dev/null; echo
    # Try py-spy but don't block
    timeout 5 /home/fabian/ComfyUI/venv/bin/py-spy dump --pid $PID 2>/dev/null | grep -E 'active|rope|sdpa|matmul|softmax|sample' | head -10 || echo "py-spy failed/timeout"
    echo "=== KILLING ==="
    kill -9 $PID 2>/dev/null || true
    sleep 2
else
    echo "No python process found"
fi

echo "=== LOG TAIL ==="
tail -10 /home/fabian/comfyui.log

echo "=== MEMORY ==="
free -h | head -2
echo 3 > /proc/sys/vm/drop_caches
free -h | head -2

echo "=== DONE ==="
