#!/usr/bin/env bash
# Priority Forge MCP diagnostic — run this when MCP tools seem flaky.
# Reports: backend health, running proxies, orphaned proxies, claude mcp list.

set -u

BACKEND_URL="http://127.0.0.1:3456/health"

color() { printf "\033[%sm%s\033[0m" "$1" "$2"; }

echo ""
echo "$(color '1;36' '━━━ Priority Forge MCP Diagnostic ━━━')"
echo ""

echo "$(color '1' '1. Backend health')"
if out=$(curl -s -m 2 "$BACKEND_URL" 2>&1); then
    echo "   $(color '32' '✓') $out"
else
    echo "   $(color '31' '✗ backend not responding on :3456')"
    echo "   Try: systemctl --user status priority-forge-backend"
fi
echo ""

echo "$(color '1' '2. Systemd backend service')"
systemctl --user is-active priority-forge-backend >/dev/null 2>&1 \
    && echo "   $(color '32' '✓') active" \
    || echo "   $(color '31' '✗ inactive — try systemctl --user start priority-forge-backend')"
echo ""

echo "$(color '1' '3. All running mcp-proxy.js processes')"
proxies=$(pgrep -af 'mcp-proxy.js' 2>/dev/null)
if [ -z "$proxies" ]; then
    echo "   (none)"
else
    while IFS= read -r line; do
        pid=$(echo "$line" | awk '{print $1}')
        etime=$(ps -o etime= -p "$pid" 2>/dev/null | tr -d ' ')
        tty=$(ps -o tty= -p "$pid" 2>/dev/null | tr -d ' ')
        ppid=$(awk '{print $4}' /proc/$pid/stat 2>/dev/null)
        marker=""
        if [ "$ppid" = "1" ]; then
            marker=" $(color '31' '← ORPHAN (ppid=1)')"
        fi
        echo "   pid=$pid ppid=$ppid tty=$tty etime=$etime$marker"
    done <<< "$proxies"
fi
echo ""

echo "$(color '1' '4. Orphaned proxies older than 60min (reaper targets)')"
orphan_count=0
for pid in $(pgrep -f 'mcp-proxy.js' 2>/dev/null); do
    ppid=$(awk '{print $4}' /proc/$pid/stat 2>/dev/null)
    [ "$ppid" = "1" ] || continue
    etime=$(ps -o etimes= -p "$pid" 2>/dev/null | tr -d ' ')
    if [ "${etime:-0}" -gt 3600 ]; then
        orphan_count=$((orphan_count + 1))
        echo "   $(color '33' "pid=$pid etime=${etime}s — eligible for reap")"
    fi
done
[ $orphan_count -eq 0 ] && echo "   (none)"
echo ""

echo "$(color '1' '5. claude mcp list')"
if command -v claude >/dev/null 2>&1; then
    claude mcp list 2>&1 | sed 's/^/   /'
else
    echo "   $(color '33' 'claude CLI not on PATH')"
fi
echo ""

echo "$(color '1' '6. Watchdog process')"
if pgrep -f 'watchdog-linux.sh' >/dev/null 2>&1; then
    pid=$(pgrep -f 'watchdog-linux.sh' | head -1)
    etime=$(ps -o etime= -p "$pid" 2>/dev/null | tr -d ' ')
    echo "   $(color '32' '✓') running (pid=$pid etime=$etime)"
else
    echo "   $(color '33' '⚠ not running — orphan reaper inactive')"
fi
echo ""

echo "$(color '1;36' '━━━ Done ━━━')"
echo ""
echo "Manual cleanup (if orphans linger):"
echo "  pkill -TERM -f mcp-proxy.js   # graceful — respects new signal handlers"
echo "  pkill -KILL -f mcp-proxy.js   # nuclear — use only if TERM didn't work"
echo ""
