#!/bin/bash
# ─────────────────────────────────────────────────────────────
# Forge pre-commit hook
# Installed by: forge new (automatically)
#               forge hooks install (manually)
#
# Runs before every git commit in a Forge-managed project.
# Blocks commit if manifest.yaml is invalid.
# ─────────────────────────────────────────────────────────────

PROJECT_NAME=$(basename "$(pwd)")
MANIFEST="manifest.yaml"

# Only run if manifest.yaml exists (safety check)
if [ ! -f "$MANIFEST" ]; then
  echo "⚠  No manifest.yaml found — skipping Forge validation"
  exit 0
fi

# Only run if manifest.yaml is staged or already tracked
if git diff --cached --name-only | grep -q "manifest.yaml" || git ls-files --error-unmatch manifest.yaml > /dev/null 2>&1; then
  echo "✦ Forge: validating manifest.yaml..."

  forge manifest "$PROJECT_NAME" --validate
  RESULT=$?

  if [ $RESULT -ne 0 ]; then
    echo ""
    echo "✗ Forge: manifest.yaml validation failed"
    echo "  Fix the errors above, then commit again."
    echo "  To skip (not recommended): git commit --no-verify"
    exit 1
  fi

  echo "✓ Forge: manifest.yaml valid"
fi

exit 0
