#!/usr/bin/env bash
# Generate a review package: commit list, stat summary, and the net
# diff with extended context, written to a file the reviewer reads in one
# call. Using the recorded per-task BASE (not HEAD~1) keeps multi-commit
# tasks intact.
#
# Usage: review-package [-C DIR] PLAN_FILE BASE HEAD [OUTFILE]
# Default OUTFILE: <repo-root>/.superpowers/sdd/<plan-basename>/review-<base7>..<head7>.diff
# (named per range, so a re-review after fixes gets a distinct fresh file).
# The repository is the one sdd-repo names; -C DIR runs as if started in DIR,
# as in sdd-workspace.
set -euo pipefail

here=$(cd "$(dirname "$0")" && pwd)
if [ "${1:-}" = "-C" ]; then
  [ -d "${2:-}" ] || { echo "bad -C directory: ${2:-}" >&2; exit 2; }
  cd "$2"
  shift 2
fi

if [ $# -lt 3 ] || [ $# -gt 4 ]; then
  echo "usage: review-package [-C DIR] PLAN_FILE BASE HEAD [OUTFILE]" >&2
  exit 2
fi

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

# Invoke via bash rather than direct exec: some extractors (Python zipfile)
# strip Unix exec bits when unpacking marketplace packages (#2040).
repo=$("${BASH:-bash}" "$here/sdd-repo" --with-commit)

git -C "$repo" rev-parse --verify --quiet "$base" >/dev/null || { echo "bad BASE: $base" >&2; exit 2; }
git -C "$repo" rev-parse --verify --quiet "$head" >/dev/null || { echo "bad HEAD: $head" >&2; exit 2; }

# Range guards (exit 3): a wrong-branch HEAD yields a range that is empty or
# not rooted at BASE; either would silently produce a bogus review package.
git -C "$repo" merge-base --is-ancestor "$base" "$head" || { echo "HEAD is not a descendant of BASE: ${base}..${head}" >&2; exit 3; }
[ "$(git -C "$repo" rev-list --count "${base}..${head}")" -gt 0 ] || { echo "empty commit range: ${base}..${head}" >&2; exit 3; }

if [ $# -eq 4 ]; then
  out=$4
else
  dir=$("${BASH:-bash}" "$here/sdd-workspace" "$plan")
  out="$dir/review-$(git -C "$repo" rev-parse --short "$base")..$(git -C "$repo" rev-parse --short "$head").diff"
fi

{
  echo "# Review package: ${base}..${head}"
  echo
  echo "## Commits"
  git -C "$repo" log --oneline "${base}..${head}"
  echo
  echo "## Files changed"
  git -C "$repo" diff --stat "${base}..${head}"
  echo
  echo "## Diff"
  git -C "$repo" diff -U10 "${base}..${head}"
} > "$out"

commits=$(git -C "$repo" rev-list --count "${base}..${head}")
echo "wrote ${out}: ${commits} commit(s), $(wc -c < "$out" | tr -d ' ') bytes"
