#!/usr/bin/env bash
# freebuff-agent — run one task brief through the Freebuff TUI inside tmux.
#
# Same contract as bin/free-agent (brief in, HANDOFF-REPORT.md out), so `handoff`
# can treat it as another backend. Freebuff has no headless mode, so this drives
# its TUI with tmux send-keys and watches the pane for the completion marker.
#
#   freebuff-agent --brief BRIEF.md --dir ~/Projects/thing [--id slug] [--timeout 1800] [--keep]
#
# Exit: 0 done, 1 failed/timeout, 2 usage.

set -uo pipefail

HOME_DIR="$HOME"
STATE="${XDG_STATE_HOME:-$HOME_DIR/.local/state}/free-agent/runs"
BRIEF=""; DIR=""; ID=""; TIMEOUT=1800; KEEP=0

while [ $# -gt 0 ]; do
  case "$1" in
    --brief) BRIEF="${2:-}"; shift 2 ;;
    --dir) DIR="${2:-}"; shift 2 ;;
    --id) ID="${2:-}"; shift 2 ;;
    --timeout) TIMEOUT="${2:-1800}"; shift 2 ;;
    --keep) KEEP=1; shift ;;
    -h|--help) sed -n '2,12p' "$0" | sed 's/^# \{0,1\}//'; exit 0 ;;
    *) echo "freebuff-agent: unknown option $1" >&2; exit 2 ;;
  esac
done

[ -n "$BRIEF" ] || { echo "freebuff-agent: --brief is required" >&2; exit 2; }
[ -f "$BRIEF" ] || { echo "freebuff-agent: no such brief $BRIEF" >&2; exit 2; }
[ -n "$DIR" ] || DIR="$(dirname "$BRIEF")"
[ -d "$DIR" ] || { echo "freebuff-agent: no such dir $DIR" >&2; exit 2; }

slug() { printf '%s' "$1" | tr '[:upper:]' '[:lower:]' | sed -E 's/[^a-z0-9]+/-/g; s/^-+|-+$//g' | cut -c1-40; }
[ -n "$ID" ] || ID="$(slug "$(basename "$BRIEF" .md)")-$(date +%H%M%S)"

RUN="$STATE/$ID"
mkdir -p "$RUN"
cp "$BRIEF" "$RUN/BRIEF.md"
LOG="$RUN/run.log"
SESSION="fb-$ID"
: > "$LOG"

write_status() { printf '%s\n' "$1" > "$RUN/status.json"; }
snap() { tmux capture-pane -p -t "$SESSION" 2>/dev/null | sed -e 's/[[:space:]]*$//' >> "$LOG"; }

write_status "{\"id\": \"$ID\", \"dir\": \"$(cd "$DIR" && pwd)\", \"state\": \"running\", \"backend\": \"freebuff\", \"startedAt\": \"$(date -u +%Y-%m-%dT%H:%M:%SZ)\"}"

tmux kill-session -t "$SESSION" 2>/dev/null
tmux new-session -d -s "$SESSION" -x 220 -y 55 -c "$DIR" "freebuff --cwd $(printf '%q' "$DIR")"
echo "[freebuff-agent] $ID: started tmux session $SESSION in $DIR"

# 1. Wait for the TUI prompt to appear.
ready=0
for _ in $(seq 1 30); do
  if tmux capture-pane -p -t "$SESSION" 2>/dev/null | grep -q "Enter a coding task"; then ready=1; break; fi
  sleep 2
done
if [ "$ready" -ne 1 ]; then
  snap; write_status "{\"id\": \"$ID\", \"state\": \"failed\", \"backend\": \"freebuff\", \"reason\": \"freebuff TUI never became ready\"}"
  echo "[freebuff-agent] $ID: TUI never became ready" >&2
  [ "$KEEP" -eq 1 ] || tmux kill-session -t "$SESSION" 2>/dev/null
  exit 1
fi

# 2. Send the task. Freebuff reads AGENTS.md itself; the brief has the specifics.
PROMPT="Read $RUN/BRIEF.md and complete it. Work only inside $DIR. When you are finished, write your report to $RUN/HANDOFF-REPORT.md (Summary, Files, Verified, Risks) and then reply with exactly HANDOFF-DONE."
tmux send-keys -t "$SESSION" "$PROMPT" Enter
echo "[freebuff-agent] $ID: task sent, waiting up to ${TIMEOUT}s"

# 3. Watch the pane. Two traps here: the task text we just sent contains the marker
#    (so a plain grep matches our own prompt), and the TUI keeps a "working..." line
#    while it thinks. So: ignore the first 30 s, require the marker on a line of its
#    own, and require the TUI to be idle (prompt back, no "working...") to believe it.
deadline=$(( $(date +%s) + TIMEOUT ))
started=$(date +%s)
state=failed
while [ "$(date +%s)" -lt "$deadline" ]; do
  sleep 10
  if ! tmux has-session -t "$SESSION" 2>/dev/null; then state=failed; break; fi
  pane="$(tmux capture-pane -p -t "$SESSION" 2>/dev/null)"
  [ $(( $(date +%s) - started )) -lt 30 ] && continue
  marker=0
  printf '%s\n' "$pane" | sed 's/[[:space:]]*$//' | grep -qx "HANDOFF-DONE" && marker=1
  busy=0
  printf '%s' "$pane" | grep -q "working\.\.\." && busy=1
  if [ "$marker" -eq 1 ] && [ "$busy" -eq 0 ]; then state=done; break; fi
  # An idle prompt with no marker is NOT completion: the TUI sits idle while it waits
  # for the model to answer, which cost one run its whole task. Only the marker ends it.
done

snap
write_status "{\"id\": \"$ID\", \"state\": \"$state\", \"backend\": \"freebuff\", \"model\": \"freebuff/deepseek\", \"endedAt\": \"$(date -u +%Y-%m-%dT%H:%M:%SZ)\", \"report\": \"$RUN/HANDOFF-REPORT.md\"}"
[ "$KEEP" -eq 1 ] || tmux kill-session -t "$SESSION" 2>/dev/null
echo "[freebuff-agent] $ID: $state ($RUN)"
[ "$state" = "done" ] && exit 0 || exit 1
