#!/bin/bash
# Wrapper script for daemon/worker to invoke claude -p with prompt from file
# Usage: run-claude.sh <prompt-file> <mcp-config-file> <max-turns> [settings-file] [channels] [model]
#
# Exit status (fix-employee-daemon-config-loss):
#   0     the CLI produced an answer, or produced nothing and had nothing to say
#   != 0  the CLI produced no answer and said why on stderr, or failed. What it
#         said is passed on to this script's stderr, for the daemon to log and
#         put in its reply.
#
# This script used to run the CLI with `2>/dev/null` and end with `exit 0`. A
# CLI that could not even start (Claude Code exits 0 after "MCP config file not
# found") was then indistinguishable from a shift with nothing to say: the
# employee answered "produced no answer: exit code 0" and no log said why
# (AGHUB-1404).

PROMPT_FILE="$1"
MCP_CONFIG="$2"
MAX_TURNS="${3:-3}"
SETTINGS_FILE="$4"
CHANNELS="$5"
MODEL="$6"

if [ ! -f "$PROMPT_FILE" ]; then
  echo "Error: prompt file not found: $PROMPT_FILE" >&2
  exit 1
fi

PROMPT="$(cat "$PROMPT_FILE")"

# Build optional flags
EXTRA_FLAGS=""
if [ -n "$SETTINGS_FILE" ] && [ -f "$SETTINGS_FILE" ]; then
  EXTRA_FLAGS="$EXTRA_FLAGS --settings $SETTINGS_FILE"
fi
if [ -n "$CHANNELS" ]; then
  EXTRA_FLAGS="$EXTRA_FLAGS --dangerously-load-development-channels $CHANNELS"
fi
if [ -n "$MODEL" ]; then
  EXTRA_FLAGS="$EXTRA_FLAGS --model $MODEL"
fi

ERR_FILE="$(mktemp 2>/dev/null || echo "${TMPDIR:-/tmp}/run-claude-err-$$")"
trap 'rm -f "$ERR_FILE"' EXIT

# stdin is closed: the prompt is an argument, and a CLI given an open stdin
# waits on it ("no stdin data received in 3s") before it starts.
OUTPUT=$(claude -p "$PROMPT" \
  --dangerously-skip-permissions \
  --max-turns "$MAX_TURNS" \
  --output-format text \
  --mcp-config "$MCP_CONFIG" \
  $EXTRA_FLAGS 2>"$ERR_FILE" </dev/null)
CODE=$?

# "Reached max turns" is the CLI's own line on stdout, and it exits non-zero
# with it. An answer that ran out of turns is still the answer.
ANSWER="$(printf '%s\n' "$OUTPUT" | grep -v "^Error: Reached max turns")"
printf '%s\n' "$ANSWER"

if [ -n "$(printf '%s' "$ANSWER" | tr -d '[:space:]')" ]; then
  # The CLI's warnings beside a real answer are noise to whoever reads the log.
  exit 0
fi

# No answer. If the CLI said why, or failed, that is the result of this run.
if [ -s "$ERR_FILE" ] || [ "$CODE" -ne 0 ]; then
  tail -c 2000 "$ERR_FILE" >&2
  [ "$CODE" -ne 0 ] && exit "$CODE"
  exit 1
fi

exit 0
