#!/bin/bash
# Git pre-push hook: Prevent accidental direct push to origin/main or GitHub/main
# Enforces the PR workflow required by AGENTS.md & .agents/rules/issue-pr-workflow.md
# Also enforces the device branch-prefix rule via .githooks/branch-guard.sh

source "$(dirname "$0")/branch-guard.sh"

remote="$1"
url="$2"
zero="0000000000000000000000000000000000000000"

while read local_ref local_oid remote_ref remote_oid; do
  # Device branch-prefix rule (.agents/rules/branch-naming.md); deletions are exempt
  case "$local_ref" in
    refs/heads/*)
      if [ "$local_oid" != "$zero" ]; then
        guard_branch_name "${local_ref#refs/heads/}" || exit 1
      fi
      ;;
  esac

  # If pushing the main branch (or pushing to remote main)
  if [ "$remote_ref" = "refs/heads/main" ] || [ "$local_ref" = "refs/heads/main" ]; then
    # When pushing to origin or GitHub (main repository)
    if [ "$remote" = "origin" ] || [ "$remote" = "GitHub" ]; then
      # Emergency override
      if [ "$ALLOW_MAIN_PUSH" = "1" ]; then
        continue
      fi

      # If deleting remote branch, let git handle or allow
      if [ "$local_oid" = "$zero" ]; then
        continue
      fi

      # Check remote head
      git fetch "$remote" main --quiet 2>/dev/null
      remote_main_oid=$(git rev-parse "$remote/main" 2>/dev/null)

      if [ -n "$remote_main_oid" ] && [ "$local_oid" = "$remote_main_oid" ]; then
        continue
      fi

      # Check if local_oid is strictly contained within remote_main_oid (e.g. older commit)
      if [ -n "$remote_main_oid" ] && git merge-base --is-ancestor "$local_oid" "$remote_main_oid" 2>/dev/null; then
        continue
      fi

      # If local_oid is not an ancestor of remote/main, then there are new unmerged commits
      new_commits=$(git rev-list "${remote_main_oid}..${local_oid}" --count 2>/dev/null || echo "1")
      echo "" >&2
      echo "🛑 [git pre-push hook] Direct push to $remote/main is blocked!" >&2
      echo "   Repository policy strictly forbids direct pushes to main." >&2
      echo "   Found $new_commits unmerged commit(s) destined for $remote/main." >&2
      echo "" >&2
      echo "   👉 Please follow the standard PR workflow:" >&2
      echo "      1. git switch -c <feature-branch>" >&2
      echo "      2. git push $remote HEAD:refs/heads/<feature-branch>" >&2
      echo "      3. gh pr create --base main --head <feature-branch>" >&2
      echo "" >&2
      echo "   (Emergency override: ALLOW_MAIN_PUSH=1 git push $remote main)" >&2
      echo "" >&2
      exit 1
    fi
  fi
done

exit 0
