#!/bin/sh
# xfce4-genmon panel indicator — polls colibri daemon health.
# Wired into a Generic Monitor panel item with 30s refresh.
# Output: genmon XML with green/red dot + agent count + task count.
#   🟢 2 agents · 3 tasks
#   🔴 daemon down

SOCKET="${COLIBRI_SOCKET:-/var/run/colibri/colibri.sock}"

have() {
    command -v "$1" >/dev/null 2>&1
}

if ! have nc || ! have python3; then
    echo "<txt>⚠ missing deps</txt>"
    echo "<tool>nc and python3 required for colibri panel indicator</tool>"
    exit 0
fi

if [ ! -S "$SOCKET" ]; then
    echo "<txt>🔴 down</txt>"
    echo "<tool>Colibri daemon not running (no socket at ${SOCKET})</tool>"
    exit 0
fi

STATUS=$(printf '{"cmd":"status"}\n' | nc -U "$SOCKET" -w 2 2>/dev/null)
if [ -z "$STATUS" ]; then
    echo "<txt>🔴 no response</txt>"
    echo "<tool>Colibri socket exists but not responding</tool>"
    exit 0
fi

AGENTS=$(echo "$STATUS" | python3 -c "import sys,json; print(json.load(sys.stdin)['data']['agents'])" 2>/dev/null)
TASKS=$(echo "$STATUS" | python3 -c "import sys,json; print(json.load(sys.stdin)['data']['tasks']['started'])" 2>/dev/null)
HOST=$(echo "$STATUS" | python3 -c "import sys,json; print(json.load(sys.stdin)['data']['host'])" 2>/dev/null)

echo "<txt>🟢 ${AGENTS:-?} agents · ${TASKS:-?} tasks</txt>"
echo "<tool>Colibri: ${HOST:-?} | socket: ${SOCKET} | agents: ${AGENTS:-?} | started tasks: ${TASKS:-?}</tool>"
echo "<txtclick>xfce4-terminal --title 'Colibri Status' --command 'colibri status'</txtclick>"
