#!/usr/bin/env bash
set -euo pipefail

REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
REF="${1:-HEAD}"
changed_files=()

usage() {
    cat <<'EOF'
Usage: ./jeannie review-last-change [REF]

Summarize a commit, show touched files, run impact analysis, and print useful
validation and rollback hints. Defaults to HEAD.
EOF
}

case "$REF" in
    -h|--help|help)
        usage
        exit 0
        ;;
esac

if ! git -C "$REPO_ROOT" rev-parse --verify "$REF" >/dev/null 2>&1; then
    echo "Unknown git ref: $REF" >&2
    exit 1
fi

echo "Jeannie Last Change Review"
echo "=========================="
echo
git -C "$REPO_ROOT" show --no-renames --stat --oneline "$REF"

echo
echo "Changed files"
mapfile -t changed_files < <(git -C "$REPO_ROOT" diff-tree --no-commit-id --name-only -r "$REF")
printf '  %s\n' "${changed_files[@]}"

echo
"${REPO_ROOT}/scripts/impact" "${changed_files[@]}"

cat <<EOF

Generic validation
  ./jeannie validate
  ./jeannie status

Rollback hint
  git revert ${REF}

Notes
  - Prefer the impact-specific validation commands above before running ./jeannie up.
  - For public route changes, validate edge and certs before app rollout.
EOF
