#!/usr/bin/env bash
# handoff — queue task briefs for free-model workers, run them in tmux, and
# hand the result back for review by the primary agent.
#
#   handoff submit BRIEF.md --dir ~/Projects/thing --role code
#   echo "..." | handoff submit - --dir . --id fix-tests
#   handoff list | status ID | log ID | review ID | kill ID | attach | clean
#   handoff daemon        # queue watcher (systemd user service runs this)
#
# State: ~/.local/share/handoff/{queue,running,done,failed}/ID.json
# Worker logs: ~/.local/state/free-agent/runs/ID/{run.log,HANDOFF-REPORT.md,status.json}

set -uo pipefail

HOME_DIR="${HOME}"
DATA="${XDG_DATA_HOME:-$HOME_DIR/.local/share}/handoff"
STATE="${XDG_STATE_HOME:-$HOME_DIR/.local/state}/free-agent/runs"
QUEUE="$DATA/queue"; RUNNING="$DATA/running"; DONE="$DATA/done"; FAILED="$DATA/failed"
TMUX_SESSION="${HANDOFF_TMUX:-handoff}"
MAX_PARALLEL="${HANDOFF_MAX_PARALLEL:-2}"
mkdir -p "$QUEUE" "$RUNNING" "$DONE" "$FAILED"

die() { printf 'handoff: %s\n' "$*" >&2; exit 1; }
now() { date -u +%Y-%m-%dT%H:%M:%SZ; }

slugify() { printf '%s' "$1" | tr '[:upper:]' '[:lower:]' | sed -E 's/[^a-z0-9]+/-/g; s/^-+|-+$//g' | cut -c1-40; }

usage() {
  sed -n '2,14p' "$0" | sed 's/^# \{0,1\}//'
  cat <<'EOF'

Roles: code (implement), review (critique a diff/design), infra (config/runbooks).
Brief format: what to change, which files, acceptance command, what not to touch.
EOF
}

need_id() { [ -n "${1:-}" ] || die "missing run id"; }
task_file() { local id="$1" d; for d in "$RUNNING" "$QUEUE" "$DONE" "$FAILED"; do [ -f "$d/$id.json" ] && { printf '%s' "$d/$id.json"; return 0; }; done; return 1; }

cmd_submit() {
  local brief="" dir="" role="code" id="" backend="free-agent"
  while [ $# -gt 0 ]; do
    case "$1" in
      --dir) dir="${2:-}"; shift 2 ;;
      --role) role="${2:-code}"; shift 2 ;;
      --id) id="${2:-}"; shift 2 ;;
      --backend) backend="${2:-free-agent}"; shift 2 ;;
      -h|--help) usage; exit 0 ;;
      -) brief="STDIN"; shift ;;
      *) brief="$1"; shift ;;
    esac
  done
  [ -n "$brief" ] || die "give a brief file, or - to read stdin"
  [ -n "$dir" ] || dir="$(pwd)"
  [ -d "$dir" ] || die "no such dir: $dir"
  dir="$(cd "$dir" && pwd)"

  local body
  if [ "$brief" = "STDIN" ]; then body="$(cat)"; else [ -f "$brief" ] || die "no such brief: $brief"; body="$(cat "$brief")"; fi
  [ -n "$body" ] || die "brief is empty"

  # Freebuff refuses prompts that read as a job handed to another agent and counts
  # them as strikes on the account, so this pipeline must not drive it.
  if [ "$backend" = "freebuff" ]; then
    die "Freebuff is not available to this queue: its usage policy blocks agent-initiated
job handoffs ('reads as a job handed to other agents') and counts an attempt as a
strike. Use it interactively, by hand. Queue the task on an API lane instead
(omit --backend, or --backend free-agent)."
  fi

  # A brief goes to a third-party API whose free tier may train on it, and whose terms
  # govern what may be sent. Refuse anything that looks like a credential: a leaked key
  # in a free-tier prompt is unrecoverable.
  if printf '%s' "$body" | grep -qE '(sk-[A-Za-z0-9_-]{16,}|gsk_[A-Za-z0-9]{16,}|AIza[0-9A-Za-z_-]{30,}|AQ\.[A-Za-z0-9_-]{20,}|-----BEGIN [A-Z ]*PRIVATE KEY-----|ghp_[A-Za-z0-9]{20,}|xox[baprs]-[A-Za-z0-9-]{10,})'; then
    die "the brief looks like it contains a credential (API key or private key). Free tiers may
train on prompts and the terms of each lane govern what may be sent. Move the value into
secretctl and reference the name instead."
  fi

  [ -n "$id" ] || id="$(slugify "$(head -c 60 <<<"$body" | tr '\n' ' ')")-$(date +%H%M%S)"
  local bpath="$DATA/$id.brief.md"
  printf '%s\n' "$body" > "$bpath"

  python3 - "$QUEUE/$id.json" "$id" "$dir" "$role" "$bpath" "$backend" <<'PY'
import json, sys, datetime
path, rid, d, role, brief, backend = sys.argv[1:7]
json.dump({"id": rid, "dir": d, "role": role, "brief": brief, "backend": backend,
           "queuedAt": datetime.datetime.now(datetime.timezone.utc).replace(tzinfo=None).isoformat()+"Z"},
          open(path, "w"), indent=1)
PY
  printf 'queued %s\n  dir:     %s\n  role:    %s\n  backend: %s\n  log:     %s/%s/run.log\n' "$id" "$dir" "$role" "$backend" "$STATE" "$id"
  echo "  start the daemon if it is not running:  handoff daemon &"
}

ensure_session() {
  tmux has-session -t "$TMUX_SESSION" 2>/dev/null && return 0
  # Start the tmux server in its own transient scope: a server started inside this
  # unit's cgroup dies with a `systemctl --user restart handoff`, taking every
  # running worker's window with it.
  systemd-run --user --scope --quiet --collect \
    tmux new-session -d -s "$TMUX_SESSION" -n workers -c "$HOME_DIR" 2>/dev/null \
    || tmux new-session -d -s "$TMUX_SESSION" -n workers -c "$HOME_DIR"
  tmux set-option -t "$TMUX_SESSION" history-limit 20000 >/dev/null 2>&1
}

running_count() { find "$RUNNING" -maxdepth 1 -name '*.json' | wc -l | tr -d ' '; }

start_task() {
  local f="$1" id dir role brief backend
  id="$(python3 -c 'import json,sys;print(json.load(open(sys.argv[1]))["id"])' "$f")"
  dir="$(python3 -c 'import json,sys;print(json.load(open(sys.argv[1]))["dir"])' "$f")"
  role="$(python3 -c 'import json,sys;d=json.load(open(sys.argv[1]));print(d.get("role","code"))' "$f")"
  brief="$(python3 -c 'import json,sys;print(json.load(open(sys.argv[1]))["brief"])' "$f")"
  backend="$(python3 -c 'import json,sys;d=json.load(open(sys.argv[1]));print(d.get("backend","free-agent"))' "$f")"

  mv "$f" "$RUNNING/$id.json" 2>/dev/null || return 0
  ensure_session
  local cmd
  if [ "$backend" = "freebuff" ]; then
    cmd="freebuff-agent --brief $(printf '%q' "$brief") --dir $(printf '%q' "$dir") --id $(printf '%q' "$id")"
  else
    cmd="free-agent --brief $(printf '%q' "$brief") --dir $(printf '%q' "$dir") --role $(printf '%q' "$role") --id $(printf '%q' "$id")"
  fi
  tmux new-window -d -t "$TMUX_SESSION" -n "$id" -c "$dir" \
    "$cmd; printf '\nhandoff window finished: %s\n' \$?; sleep 2" \
    >/dev/null 2>&1 || { echo "handoff: tmux failed for $id" >&2; mv "$RUNNING/$id.json" "$FAILED/$id.json"; return 1; }
  echo "[$(now)] started $id ($backend/$role) in $dir"
}

collect_finished() {
  local f id st
  for f in "$RUNNING"/*.json; do
    [ -e "$f" ] || continue
    id="$(basename "$f" .json)"
    st="$STATE/$id/status.json"
    [ -f "$st" ] || continue
    local state
    state="$(python3 -c 'import json,sys;print(json.load(open(sys.argv[1])).get("state","?"))' "$st" 2>/dev/null)"
    case "$state" in
      done) mv "$f" "$DONE/$id.json"; echo "[$(now)] done $id -> $(dirname "$st")/HANDOFF-REPORT.md" ;;
      failed|no-capacity) mv "$f" "$FAILED/$id.json"; echo "[$(now)] $state $id" ;;
    esac
    if [ -n "${state:-}" ] && [ "$state" != "running" ]; then
      tmux list-windows -t "$TMUX_SESSION" -F '#{window_name}' 2>/dev/null | grep -qx "$id" && tmux kill-window -t "$TMUX_SESSION:$id" 2>/dev/null
    fi
  done
}

# A task can land in running/ and then lose its worker (daemon restart, killed
# window, tmux server death). Put it back in the queue instead of leaving it
# "running" forever.
requeue_orphans() {
  local f id
  for f in "$RUNNING"/*.json; do
    [ -e "$f" ] || continue
    id="$(basename "$f" .json)"
    tmux list-windows -t "$TMUX_SESSION" -F '#{window_name}' 2>/dev/null | grep -qx "$id" && continue
    pgrep -f -- "--id $id" >/dev/null 2>&1 && continue
    mv "$f" "$QUEUE/$id.json" 2>/dev/null && echo "[$(now)] requeued orphan $id"
  done
}

cmd_daemon() {
  ensure_session
  echo "[$(now)] handoff daemon: queue=$QUEUE parallel=$MAX_PARALLEL session=$TMUX_SESSION"
  requeue_orphans
  local unpaused="$DATA/pause"
  trap 'echo "[$(now)] handoff daemon: stopping"; exit 0' INT TERM
  while :; do
    if [ ! -f "$unpaused" ]; then
      collect_finished
      requeue_orphans
      for f in "$QUEUE"/*.json; do
        [ -e "$f" ] || continue
        [ "$(running_count)" -lt "$MAX_PARALLEL" ] || break
        start_task "$f"
      done
    fi
    sleep 5
  done
}

cmd_list() {
  local d id st
  for d in queue running done failed; do
    for f in "$DATA/$d"/*.json; do
      [ -e "$f" ] || continue
      id="$(basename "$f" .json)"
      st="$STATE/$id/status.json"
      local model="-"
      [ -f "$st" ] && model="$(python3 -c 'import json,sys;d=json.load(open(sys.argv[1]));print(d.get("model") or d.get("backend") or d.get("state","-"))' "$st" 2>/dev/null)"
      local tag="$d"
      if [ "$d" = "running" ] && ! tmux list-windows -t "$TMUX_SESSION" -F '#{window_name}' 2>/dev/null | grep -qx "$id"; then
        tag="orphan"
      fi
      printf '%-8s %-28s %-34s %s\n' "$tag" "$id" "$model" "$(dirname "$st")"
    done
  done
}

cmd_status() { need_id "${1:-}"; local id="$1" f; f="$(task_file "$id")" || die "unknown id $id"; echo "task: $f"; cat "$f"; echo; [ -f "$STATE/$id/status.json" ] && cat "$STATE/$id/status.json"; }

cmd_log() { need_id "${1:-}"; local id="$1" n="${2:-120}"; tail -n "$n" "$STATE/$id/run.log" 2>/dev/null || die "no log for $id"; }

cmd_review() {
  need_id "${1:-}"; local id="$1"
  local dir=""; [ -f "$DATA/done/$id.json" ] && dir="$(python3 -c 'import json,sys;print(json.load(open(sys.argv[1]))["dir"])' "$DATA/done/$id.json")"
  [ -n "$dir" ] || [ -f "$DATA/running/$id.json" ] && dir="$(python3 -c 'import json,sys;print(json.load(open(sys.argv[1]))["dir"])' "$DATA/running/$id.json" 2>/dev/null)"
  echo "== status =="; cat "$STATE/$id/status.json" 2>/dev/null || echo "(no status yet)"
  echo; echo "== report =="; cat "$STATE/$id/HANDOFF-REPORT.md" 2>/dev/null || echo "(no report written)"
  if [ -n "$dir" ] && [ -d "$dir/.git" ]; then
    echo; echo "== working tree =="; git -C "$dir" status --short | head -40
    echo; echo "== diffstat =="; git -C "$dir" diff --stat | tail -20
    echo; echo "review with:  git -C $dir diff   (or 'git add -p' to stage selectively)"
  fi
}

cmd_kill() {
  need_id "${1:-}"; local id="$1"
  tmux kill-window -t "$TMUX_SESSION:$id" 2>/dev/null && echo "killed window $id" || echo "no tmux window $id"
  pkill -f "free-agent --brief .*--id $id" 2>/dev/null && echo "stopped worker" || true
  for d in queue running; do [ -f "$DATA/$d/$id.json" ] && mv "$DATA/$d/$id.json" "$FAILED/$id.json" && echo "moved task to failed/"; done
}

cmd_pause()  { touch "$DATA/pause"; echo "daemon paused (existing runs continue)"; }
cmd_resume() { rm -f "$DATA/pause"; echo "daemon resumed"; }

cmd_clean() {
  local days="${1:-7}"
  find "$DATA/done" "$DATA/failed" -name '*.json' -mtime +"$days" -delete 2>/dev/null
  find "$STATE" -maxdepth 1 -type d -mtime +"$days" -name '*-*' -exec rm -rf {} + 2>/dev/null
  echo "removed runs older than $days days"
}

cmd_attach() { ensure_session; exec tmux attach -t "$TMUX_SESSION"; }

case "${1:-}" in
  submit) shift; cmd_submit "$@" ;;
  daemon) cmd_daemon ;;
  list|ls) cmd_list ;;
  status) shift; cmd_status "$@" ;;
  log|tail) shift; cmd_log "$@" ;;
  review) shift; cmd_review "$@" ;;
  kill) shift; cmd_kill "$@" ;;
  attach) cmd_attach ;;
  pause) cmd_pause ;;
  resume) cmd_resume ;;
  clean) shift; cmd_clean "$@" ;;
  -h|--help|help|"") usage ;;
  *) usage; exit 2 ;;
esac
