#!/usr/bin/env bash
# ollie:parallel read
# args_json: {"type":"object","required":["pid"],"properties":{"pid":{"type":"string","description":"Process PID"}}}
# ollie:prompt
# ## process_output
#
# Read output from a detached background process (last 64KB ring buffer).
#
# ```
# process_output(pid="12345")
# ```
# ollie:end

set -euo pipefail

source "$(dirname "$0")/_lib/args.sh"

pid=$(arg_require "pid")
session="${OLLIE_SESSION_ID:?OLLIE_SESSION_ID not set}"

# Find agent (use first agent in session)
agent=$(ollie-9p ls "session/$session/agent" 2>/dev/null | grep -v '^new$' | head -1)
[ -z "$agent" ] && { echo "error: no agent in session" >&2; exit 1; }

result=$(ollie-9p read "session/$session/agent/$agent/proc/$pid" 2>&1) || {
    echo "(no output captured yet)"
    exit 0
}

if [ -z "$result" ]; then
    echo "(no output captured yet)"
else
    echo "$result"
fi
