#!/usr/bin/env bash
# Close one task of an inline plan execution in a single call: run the task's
# test command, keep its full output in the workspace, print the tail, and —
# only if the command succeeded — append the completion line to the ledger.
# A failing command records nothing: the task is not complete.
#
# Usage: task-done SPEC_FILE TASK_NUMBER BASE [SHA... | --uncommitted] -- TEST_COMMAND [ARGS...]
#   BASE is the SHA task-start printed; the completion line records BASE..HEAD,
#   the listed SHAs when other agents commit to the same branch, or
#   "uncommitted" for exploratory work that commits nothing.
# Exit: the test command's exit status.
set -euo pipefail

usage() {
  echo "usage: task-done SPEC_FILE TASK_NUMBER BASE [SHA... | --uncommitted] -- TEST_COMMAND [ARGS...]" >&2
  exit 2
}

[ $# -ge 5 ] || usage
plan=$1
n=$2
base=$3
shift 3
shas=()
while [ $# -gt 0 ] && [ "$1" != "--" ]; do
  shas+=("$1")
  shift
done
[ $# -ge 2 ] || usage
shift
sdd="$(cd "$(dirname "$0")" && pwd)"

git rev-parse --verify --quiet "$base" > /dev/null || {
  echo "bad BASE: $base" >&2
  exit 2
}
recorded="commits $(git rev-parse --short=7 "$base")..$(git rev-parse --short=7 HEAD)"
if [ ${#shas[@]} -eq 1 ] && [ "${shas[0]}" = "--uncommitted" ]; then
  recorded="uncommitted"
elif [ ${#shas[@]} -gt 0 ]; then
  recorded="commits"
  for c in "${shas[@]}"; do
    git rev-parse --verify --quiet "$c^{commit}" > /dev/null || {
      echo "bad SHA: $c" >&2
      exit 2
    }
    recorded="$recorded $(git rev-parse --short=7 "$c")"
  done
fi

dir=$("$sdd/sdd-workspace" "$plan")
log="$dir/task-${n}-tests.log"
ledger="$dir/progress.md"

# Render the command the way a person would type it, for the ledger line.
cmd=""
for a in "$@"; do
  case "$a" in
    *[[:space:]\"\;\|\&]*) cmd="$cmd '$a'" ;;
    *) cmd="$cmd $a" ;;
  esac
done
cmd=${cmd# }

rc=0
"$@" > "$log" 2>&1 || rc=$?

tail -n 5 "$log"
if [ "$rc" -ne 0 ]; then
  echo "task-done: test command exited $rc; Task $n NOT recorded (full output: $log)" >&2
  exit "$rc"
fi

last=$(grep -v '^[[:space:]]*$' "$log" | tail -n 1) || last="(no output)"
[ -f "$ledger" ] || printf '# SDD ledger — plan: %s\n' "$plan" > "$ledger"
line="Task $n: complete ($recorded, tests: $cmd → $last)"
printf '%s\n' "$line" >> "$ledger"
echo "ledger: $line"
