#!/usr/bin/env bash
# check-docker-prep-staged — pre-commit guard for docker-prep.sh artifacts.
#
# Blocks commits that contain:
#   1. package.json with rewritten "file:../.docker-deps/" refs
#   2. Staged .docker-deps/*.tgz tarballs
#   3. Staged package.json.bak backup files
#
# Phase B4 of docker-build-optimization-roadmap.md.
# Returns non-zero (blocks commit) if any artifact is found.

set -uo pipefail

# Only run inside a git working tree
git rev-parse --show-toplevel >/dev/null 2>&1 || exit 0

STAGED=$(git diff --cached --name-only --diff-filter=ACMR 2>/dev/null)
if [[ -z "$STAGED" ]]; then
  exit 0
fi

fail=0

# 1. Rewritten package.json refs
REWRITTEN=$(echo "$STAGED" | grep -E '(^|/)package\.json$' | while read -r f; do
  [[ -f "$f" ]] || continue
  if grep -l '"file:\.\./\.docker-deps/\|"file:\.docker-deps/' "$f" 2>/dev/null; then
    :
  fi
done)
if [[ -n "$REWRITTEN" ]]; then
  echo "❌ docker-prep artifacts staged: rewritten package.json detected"
  echo "$REWRITTEN" | sed 's/^/    /'
  echo "   Run: bash scripts/docker-prep.sh --restore"
  fail=1
fi

# 2. Tarballs
TARBALLS=$(echo "$STAGED" | grep -E '\.docker-deps/.*\.tgz$' || true)
if [[ -n "$TARBALLS" ]]; then
  echo "❌ Staged docker-prep tarballs (must not be committed):"
  echo "$TARBALLS" | sed 's/^/    /'
  echo "   Run: bash scripts/docker-prep.sh --restore"
  fail=1
fi

# 3. Backup files
BAKS=$(echo "$STAGED" | grep -E '(^|/)package\.json\.bak$' || true)
if [[ -n "$BAKS" ]]; then
  echo "❌ Staged package.json.bak files (must not be committed):"
  echo "$BAKS" | sed 's/^/    /'
  echo "   Run: bash scripts/docker-prep.sh --restore"
  fail=1
fi

exit $fail
