#!/usr/bin/env bash
# Seed a session handoff/changelog with git + PR context.
# Usage:  bash collect-context.sh [since-ref]
#   since-ref: base to diff against (default: origin/main, else the last 20 commits).
set -uo pipefail

SINCE="${1:-origin/main}"
echo "════════════════════════════════════════════════════════════"
echo " SESSION HANDOFF CONTEXT — $(git rev-parse --show-toplevel 2>/dev/null || echo 'not a git repo')"
echo "════════════════════════════════════════════════════════════"

if ! git rev-parse --git-dir >/dev/null 2>&1; then
  echo "(not a git repository — gather changed files manually)"; exit 0
fi

echo
echo "── Current branch ──"
git branch --show-current

echo
echo "── Uncommitted changes (working tree) ──"
git status --porcelain | head -50
[ -z "$(git status --porcelain)" ] && echo "(clean)"

echo
echo "── Recent commits (last 20) ──"
git log --oneline -20

echo
echo "── Commits since ${SINCE} (if it exists) ──"
if git rev-parse "$SINCE" >/dev/null 2>&1; then
  git log --oneline "${SINCE}..HEAD" 2>/dev/null | head -40
  echo
  echo "── Files changed since ${SINCE} ──"
  git diff --stat "$SINCE" 2>/dev/null | tail -40
else
  echo "(ref ${SINCE} not found — skipping)"
fi

if command -v gh >/dev/null 2>&1; then
  echo
  echo "── Open PRs ──"
  gh pr list --state open --limit 20 2>/dev/null || echo "(gh: no access or no PRs)"
  echo
  echo "── Recently merged PRs (last 10) ──"
  gh pr list --state merged --limit 10 2>/dev/null || true
fi

echo
echo "════════════════════════════════════════════════════════════"
echo " Now fill assets/handoff-template.md using the above."
echo " Verify each 'done' claim against reality before writing it."
echo "════════════════════════════════════════════════════════════"
