#!/usr/bin/env bash
# Poll for deferred agent_respond-jobber og returner info for Claude Code.
# Brukes av Claude Code sin cron-loop.
#
# Output: JSON med jobb-info hvis det finnes en jobb, ellers "none"

set -euo pipefail

CHAT_ID="abe2edfd-986b-45ba-8c2e-4461a8a7e480"

# Hent eldste deferred jobb
JOB=$(docker exec sidelinja-postgres-1 psql -U sidelinja -d synops -t -A -c "
SELECT row_to_json(t) FROM (
    SELECT j.id as job_id, j.payload, j.created_at,
           n.content as message,
           n.created_by as sender_id,
           (SELECT title FROM nodes WHERE id = n.created_by) as sender_name
    FROM job_queue j
    JOIN nodes n ON n.id = (j.payload->>'message_id')::uuid
    WHERE j.job_type = 'agent_respond'
    AND j.status = 'deferred'
    ORDER BY j.created_at ASC
    LIMIT 1
) t;
" 2>/dev/null)

if [ -z "$JOB" ] || [ "$JOB" = "" ]; then
    echo "none"
    exit 0
fi

echo "$JOB"
