#!/usr/bin/env bash
# ollie:parallel read
# description: Read stdout/stderr output from a detached background process. Returns the last 64KB of combined output.
# Args: <pid>

set -euo pipefail

pid="${1:?usage: process_output <pid>}"
session="${OLLIE_SESSION_ID:?OLLIE_SESSION_ID not set}"

# Use gdbus for proper parsing of string with newlines
result=$(gdbus call --session --dest org.ollie.SessionManager \
  --object-path /org/ollie/SessionManager \
  --method org.ollie.SessionManager.GetDetachedOutput "$session" "$pid" 2>&1)

# gdbus wraps in ('...',) - strip the outer tuple
result=$(echo "$result" | sed "s/^('//;s/',)$//")

if [ -z "$result" ]; then
    echo "(no output captured yet)"
else
    # Unescape gdbus string escaping
    echo -e "$result"
fi
