#!/usr/bin/env bash
# Extract one task's full text from an implementation plan into a file the
# implementer reads in one call, so the task text never has to be pasted
# through the controller's context.
#
# Usage: task-brief PLAN_FILE TASK_NUMBER [OUTFILE]
# Default OUTFILE: <repo-root>/.outline/sdd/task-<N>-brief.md
# (per worktree; concurrent runs in the same working tree share it).
set -euo pipefail

if [ $# -lt 2 ] || [ $# -gt 3 ]; then
  echo "usage: task-brief PLAN_FILE TASK_NUMBER [OUTFILE]" >&2
  exit 2
fi

plan=$1
n=$2
[ -f "$plan" ] || { echo "no such plan file: $plan" >&2; exit 2; }

if [ $# -eq 3 ]; then
  out=$3
else
  here=$(cd "$(dirname "$0")" && pwd)
  dir=$("$here/sd-workspace")
  out="$dir/task-${n}-brief.md"
fi

# A task runs from its "Task N" heading until the next heading at the same or
# shallower depth (a sibling task or a global section like "Acceptance
# Criteria"). Deeper headings are the task's own subsections and stay in. This
# stops sibling/global sections bleeding into the brief — the brief is the
# implementer's single source of requirements, so foreign prose is scope creep.
awk -v n="$n" '
  /^```/ { infence = !infence; if (intask) print; next }
  !infence && /^#+[ \t]/ {
    match($0, /^#+/); d = RLENGTH
    if ($0 ~ ("^#+[ \t]+Task[ \t]+" n "([^0-9]|$)")) { intask = 1; taskdepth = d; print; next }
    if (intask && d <= taskdepth) intask = 0
  }
  intask { print }
' "$plan" > "$out"

if [ ! -s "$out" ]; then
  echo "task ${n} not found in ${plan} (no heading matching 'Task ${n}')" >&2
  exit 3
fi

echo "wrote ${out}: $(wc -l < "$out" | tr -d ' ') lines"
