#!/usr/bin/env bash
# ask_claude.sh — Submit a question to the Claude daemon and wait for the response.
#
# Designed to be called by Codex (or any tool in a restricted sandbox) that can write
# files but cannot directly execute the claude binary.
#
# The Claude daemon (claude_daemon.sh) must be running.
#
# Usage:
#   ask_claude.sh "question"
#   ask_claude.sh -q question_file.md
#   ask_claude.sh -f context.java -f other.java "question"
#
# Options:
#   -f FILE     Embed file contents in the prompt (repeatable)
#   -q FILE     Read question text from a file
#   -t SECS     Timeout waiting for response (default: 180)
#   -o FILE     Write response to FILE in addition to stdout
#   -h          Show help
#
# Exit codes:
#   0  success
#   1  bad arguments
#   2  daemon timeout (no response within -t seconds)
#   3  daemon returned an error response

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
WORKSPACE_ROOT="$(cd "$SCRIPT_DIR/../../.." && pwd)"
INBOX_DIR="${CLAUDE_DAEMON_INBOX:-$WORKSPACE_ROOT/attic/CLAUDE/daemon/inbox}"

CONTEXT_FILES=()
QUESTION=""
QUESTION_FILE=""
TIMEOUT_SEC=180
OUTPUT_FILE=""

while getopts "f:q:t:o:h" opt; do
  case "$opt" in
    f) CONTEXT_FILES+=("$OPTARG") ;;
    q) QUESTION_FILE="$OPTARG" ;;
    t) TIMEOUT_SEC="$OPTARG" ;;
    o) OUTPUT_FILE="$OPTARG" ;;
    h) awk 'NR==1{next} /^#/{gsub(/^# ?/,""); print; next} {exit}' "$0"; exit 0 ;;
    *) echo "Unknown flag: -$OPTARG" >&2; exit 1 ;;
  esac
done
shift $((OPTIND - 1))

# ── Build question ────────────────────────────────────────────────────────────

if [[ -n "$QUESTION_FILE" ]]; then
  [[ -f "$QUESTION_FILE" ]] || { echo "ERROR: question file not found: $QUESTION_FILE" >&2; exit 1; }
  QUESTION="$(cat "$QUESTION_FILE")"
elif [[ $# -gt 0 ]]; then
  QUESTION="$*"
else
  echo "ERROR: provide a question via -q FILE or as a positional argument." >&2; exit 1
fi

# ── Build prompt ──────────────────────────────────────────────────────────────

PROMPT="$QUESTION"
for f in "${CONTEXT_FILES[@]}"; do
  if [[ -f "$f" ]]; then
    PROMPT+=$'\n\n'"--- FILE: $f ---"$'\n'"$(cat "$f")"$'\n'"--- END FILE ---"
  else
    echo "WARNING: context file not found: $f" >&2
  fi
done

# ── Submit request ────────────────────────────────────────────────────────────

mkdir -p "$INBOX_DIR"
TS="$(date +%Y%m%d_%H%M%S)_$$"
REQ_FILE="$INBOX_DIR/${TS}.request"
RESP_FILE="$INBOX_DIR/${TS}.response"
ERR_FILE="$INBOX_DIR/${TS}.error"

echo "$PROMPT" > "$REQ_FILE"

# ── Poll for response ─────────────────────────────────────────────────────────

ELAPSED=0
while true; do
  if [[ -f "$RESP_FILE" ]]; then
    # Check if daemon reported an error
    if [[ -f "$ERR_FILE" ]] || grep -q '^DAEMON ERROR:' "$RESP_FILE" 2>/dev/null; then
      echo "ERROR: Claude daemon reported a failure." >&2
      cat "$RESP_FILE" >&2
      [[ -f "$ERR_FILE" ]] && cat "$ERR_FILE" >&2
      exit 3
    fi
    if [[ -n "$OUTPUT_FILE" ]]; then
      cp "$RESP_FILE" "$OUTPUT_FILE"
    fi
    cat "$RESP_FILE"
    exit 0
  fi

  if [[ $ELAPSED -ge $TIMEOUT_SEC ]]; then
    echo "ERROR: timeout after ${TIMEOUT_SEC}s — is claude_daemon.sh running?" >&2
    rm -f "$REQ_FILE"
    exit 2
  fi

  sleep 2
  ELAPSED=$((ELAPSED + 2))
done
