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

ROOT_DIR="$(git rev-parse --show-toplevel)"
# shellcheck source=_common.sh
source "${ROOT_DIR}/.githooks/_common.sh"

if [[ "${SKIP_GIT_HOOKS:-}" == "1" ]]; then
  exit 0
fi

zero="0000000000000000000000000000000000000000"
need_migration_check=0
need_frontend_build=0

while read -r local_ref local_sha remote_ref remote_sha; do
  [[ "${local_sha}" == "${zero}" ]] && continue

  changed_files=""
  if [[ "${remote_sha}" == "${zero}" ]]; then
    upstream_ref="$(git rev-parse --abbrev-ref --symbolic-full-name '@{u}' 2>/dev/null || true)"
    if [[ -n "${upstream_ref}" ]]; then
      remote_branch="${upstream_ref#*/}"
      remote_name="${upstream_ref%%/*}"
      merge_base="$(git merge-base "${local_sha}" "${remote_name}/${remote_branch}" 2>/dev/null || true)"
      if [[ -n "${merge_base}" ]]; then
        changed_files="$(git diff --name-only --diff-filter=ACMR "${merge_base}" "${local_sha}" || true)"
      fi
    fi
    if [[ -z "${changed_files}" ]]; then
      changed_files="$(git diff-tree --no-commit-id --name-only --diff-filter=ACMR -r "${local_sha}" || true)"
    fi
  else
    changed_files="$(git diff --name-only --diff-filter=ACMR "${remote_sha}" "${local_sha}" || true)"
  fi

  if echo "${changed_files}" | grep -qE '^backend/migrations/versions/.*\.py$'; then
    need_migration_check=1
  fi

  if frontend_paths_in "${changed_files}"; then
    need_frontend_build=1
  fi
done

if [[ "${need_migration_check}" -eq 1 ]]; then
  if ! run_migration_heads_check "${ROOT_DIR}"; then
    exit 1
  fi
fi

if [[ "${SKIP_FRONTEND_HOOKS:-}" == "1" ]]; then
  exit 0
fi

if [[ "${need_frontend_build}" -eq 0 ]]; then
  exit 0
fi

if ! run_frontend_build "${ROOT_DIR}"; then
  echo "[pre-push] 前端 build 失败，已阻止 push。"
  echo "[pre-push] 跳过检查可设置: SKIP_FRONTEND_HOOKS=1 git push"
  echo "[pre-push] 或跳过全部 hook: git push --no-verify"
  exit 1
fi

echo "[pre-push] 前端 build 通过。"
exit 0
