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

# Pre-push hook: run local CI-style analysis on files changed in the push.

repo_root=$(git rev-parse --show-toplevel 2> /dev/null || pwd)
cd "$repo_root"

remote_name="${1:-origin}"
remote_url="${2:-}"

# Controls:
# - MBE_HOOK_FAIL_ON_MISSING_TOOLS: 1|0 (default: 0)
#   when 1, missing analyzers make the hook fail.
# - MBE_HOOK_RUN_SCAN_BUILD: 1|0 (default: 0)
#   when 1, also runs the heavier full scan-build pass.
FAIL_ON_MISSING_TOOLS="${MBE_HOOK_FAIL_ON_MISSING_TOOLS:-0}"
RUN_SCAN_BUILD="${MBE_HOOK_RUN_SCAN_BUILD:-0}"

if [[ -n "$remote_url" ]]; then
  echo "pre-push: remote=${remote_name} url=<provided>"
else
  echo "pre-push: remote=${remote_name} url=<none>"
fi

zeros="0000000000000000000000000000000000000000"

# tools/push_changed_files.sh lists each pushed ref's changed paths, raw and
# NUL-separated, and fails rather than report "nothing changed" when it cannot
# compute them; the list goes through a private temporary file outside the
# checkout.
push_paths_file=$(mktemp "${TMPDIR:-/tmp}/mbelib-neo-pre-push-paths.XXXXXX")
trap 'rm -f "$push_paths_file"' EXIT

head_sha=$(git rev-parse -q --verify HEAD 2> /dev/null || true)

changed_paths=()
head_changed_paths=()
while read -r local_ref local_sha _remote_ref remote_sha; do
  # Deleting a ref; nothing to analyze.
  if [[ "$local_sha" == "$zeros" ]]; then
    continue
  fi

  # Tags are often pushed in bulk and aren't useful for static analysis gating.
  if [[ "$local_ref" == refs/tags/* ]]; then
    continue
  fi

  if ! tools/push_changed_files.sh "$remote_name" "$local_ref" "$local_sha" "$remote_sha" > "$push_paths_file"; then
    echo "pre-push: could not list the files ${local_ref} changes; not pushing unchecked." >&2
    exit 1
  fi
  mapfile -d '' -t diff_files < "$push_paths_file"
  # The checks below handle paths one per line, so a name with a newline in it
  # would split into two paths that do not exist: skipped with a warning for a
  # ref that is not checked out, or a misleading "local deletions" failure for
  # the one that is.
  for p in "${diff_files[@]}"; do
    if [[ "$p" == *$'\n'* ]]; then
      printf 'pre-push: %s changes a path with a newline in it, which the checks cannot handle: %q\n' "$local_ref" "$p" >&2
      exit 1
    fi
  done
  changed_paths+=("${diff_files[@]}")
  if [[ -n "$head_sha" && "$local_sha" == "$head_sha" ]]; then
    head_changed_paths+=("${diff_files[@]}")
  fi
done

if [[ ${#changed_paths[@]} -eq 0 ]]; then
  exit 0
fi

mapfile -t changed_paths < <(printf '%s\n' "${changed_paths[@]}" | sort -u)
if [[ ${#head_changed_paths[@]} -gt 0 ]]; then
  mapfile -t head_changed_paths < <(printf '%s\n' "${head_changed_paths[@]}" | sort -u)
fi

declare -A head_changed_lookup=()
for p in "${head_changed_paths[@]}"; do
  head_changed_lookup["$p"]=1
done

changed_sources=()
changed_headers=()
format_files=()
cmake_format_files=()
semgrep_targets=()
shell_lint_targets=()
workflow_lint_targets=()
workflow_security_targets=()
dependency_scan_targets=()
missing_worktree_paths=()
skipped_missing_paths=()
for p in "${changed_paths[@]}"; do
  case "$p" in
    build/* | src/external/*) continue ;;
  esac

  track_semgrep=0
  case "$p" in
    src/* | include/* | examples/* | bench/* | tests/* | tools/* | .github/workflows/*.yml | .github/workflows/*.yaml)
      track_semgrep=1
      ;;
  esac

  case "$p" in
    *.sh | .githooks/*) shell_lint_targets+=("$p") ;;
    .github/workflows/*.yml | .github/workflows/*.yaml) workflow_lint_targets+=("$p") ;;
  esac

  case "$p" in
    CMakeLists.txt | */CMakeLists.txt | CMakeLists.txt.in | */CMakeLists.txt.in | *.cmake | *.cmake.in)
      cmake_format_files+=("$p")
      ;;
  esac

  case "$p" in
    .github/workflows/*.yml | .github/workflows/*.yaml | .github/dependabot.yml | .github/zizmor.yml)
      workflow_security_targets+=("$p")
      ;;
  esac

  case "$p" in
    .github/dependabot.yml | tools/osv_scan.sh | src/external/* | tools/ci-dependency-pins.env | cmake/Pffft.cmake | tools/update_pffft.py | tools/update_aur_pffft.py | tools/pffft_metadata.py | CMakeLists.txt)
      dependency_scan_targets+=("$p")
      ;;
  esac

  track_c_family=0
  case "$p" in
    *.c | *.cc | *.cpp | *.cxx | *.h | *.hh | *.hpp | *.hxx) track_c_family=1 ;;
  esac

  if [[ ! -e "$p" && ! -L "$p" ]]; then
    if [[ $track_semgrep -eq 1 || $track_c_family -eq 1 ]]; then
      if [[ -n "${head_changed_lookup[$p]:-}" ]]; then
        missing_worktree_paths+=("$p")
      else
        skipped_missing_paths+=("$p")
      fi
    fi
    continue
  fi

  if [[ $track_semgrep -eq 1 ]]; then
    semgrep_targets+=("$p")
  fi

  case "$p" in
    *.c | *.cc | *.cpp | *.cxx)
      changed_sources+=("$p")
      format_files+=("$p")
      ;;
    *.h | *.hh | *.hpp | *.hxx)
      changed_headers+=("$p")
      format_files+=("$p")
      ;;
  esac
done

if [[ ${#format_files[@]} -gt 0 ]]; then
  mapfile -t format_files < <(printf '%s\n' "${format_files[@]}" | sort -u)
fi
if [[ ${#semgrep_targets[@]} -gt 0 ]]; then
  mapfile -t semgrep_targets < <(printf '%s\n' "${semgrep_targets[@]}" | sort -u)
fi
if [[ ${#cmake_format_files[@]} -gt 0 ]]; then
  mapfile -t cmake_format_files < <(printf '%s\n' "${cmake_format_files[@]}" | sort -u)
fi
if [[ ${#shell_lint_targets[@]} -gt 0 ]]; then
  mapfile -t shell_lint_targets < <(printf '%s\n' "${shell_lint_targets[@]}" | sort -u)
fi
if [[ ${#workflow_lint_targets[@]} -gt 0 ]]; then
  mapfile -t workflow_lint_targets < <(printf '%s\n' "${workflow_lint_targets[@]}" | sort -u)
fi
if [[ ${#workflow_security_targets[@]} -gt 0 ]]; then
  mapfile -t workflow_security_targets < <(printf '%s\n' "${workflow_security_targets[@]}" | sort -u)
fi
if [[ ${#dependency_scan_targets[@]} -gt 0 ]]; then
  mapfile -t dependency_scan_targets < <(printf '%s\n' "${dependency_scan_targets[@]}" | sort -u)
fi
if [[ ${#skipped_missing_paths[@]} -gt 0 ]]; then
  mapfile -t skipped_missing_paths < <(printf '%s\n' "${skipped_missing_paths[@]}" | sort -u)
  echo "pre-push: skipping pushed paths absent from current checkout (non-checked-out ref likely):" >&2
  printf '  %s\n' "${skipped_missing_paths[@]}" >&2
fi
if [[ ${#missing_worktree_paths[@]} -gt 0 ]]; then
  mapfile -t missing_worktree_paths < <(printf '%s\n' "${missing_worktree_paths[@]}" | sort -u)
  echo "pre-push: unable to analyze pushed paths missing from current worktree for the checked-out ref:" >&2
  printf '  %s\n' "${missing_worktree_paths[@]}" >&2
  echo "pre-push: restore local deletions or push from a clean checkout and retry." >&2
  exit 1
fi

analysis_tus=("${changed_sources[@]}")

escape_rg() {
  printf '%s' "$1" | sed -e 's/[][(){}.^$*+?|\\]/\\&/g'
}

MAX_TUS_PER_HEADER_PER_LANGUAGE=5
collect_header_includers() {
  local pattern="$1"
  local c_file=""
  local cxx_file=""
  local c_matches=()
  local cxx_matches=()

  mapfile -t c_matches < <(
    rg -l --glob '!src/external/**' \
      -g'*.c' \
      "$pattern" src tests examples bench 2> /dev/null |
      sort |
      head -n "$MAX_TUS_PER_HEADER_PER_LANGUAGE" || true
  )
  mapfile -t cxx_matches < <(
    rg -l --glob '!src/external/**' \
      -g'*.cc' -g'*.cpp' -g'*.cxx' \
      "$pattern" src tests examples bench 2> /dev/null |
      sort |
      head -n "$MAX_TUS_PER_HEADER_PER_LANGUAGE" || true
  )

  for c_file in "${c_matches[@]}"; do
    printf '%s\n' "$c_file"
  done
  for cxx_file in "${cxx_matches[@]}"; do
    printf '%s\n' "$cxx_file"
  done
}

if [[ ${#changed_headers[@]} -gt 0 ]]; then
  if command -v rg > /dev/null 2>&1; then
    for hdr in "${changed_headers[@]}"; do
      include_key=""
      if [[ "$hdr" == include/* ]]; then
        include_key="${hdr#include/}"
        include_key=$(escape_rg "$include_key")
        pattern="^[[:space:]]*#[[:space:]]*include[[:space:]]*[<\\\"]${include_key}[>\\\"]"
      else
        base=$(basename "$hdr")
        base=$(escape_rg "$base")
        pattern="^[[:space:]]*#[[:space:]]*include[[:space:]]*[<\\\"][^>\\\"]*${base}[>\\\"]"
      fi

      mapfile -t matches < <(collect_header_includers "$pattern")
      analysis_tus+=("${matches[@]}")
    done
  else
    echo "pre-push: rg not found; header include expansion skipped." >&2
  fi
fi

if [[ ${#analysis_tus[@]} -gt 0 ]]; then
  mapfile -t analysis_tus < <(printf '%s\n' "${analysis_tus[@]}" | sort -u)
fi

echo "pre-push: changed paths=${#changed_paths[@]} sources=${#changed_sources[@]}" \
  "headers=${#changed_headers[@]} tus=${#analysis_tus[@]}"

cppcheck_sources=()
for p in "${analysis_tus[@]}"; do
  case "$p" in
    src/*) cppcheck_sources+=("$p") ;;
  esac
done
if [[ ${#cppcheck_sources[@]} -gt 0 ]]; then
  mapfile -t cppcheck_sources < <(printf '%s\n' "${cppcheck_sources[@]}" | sort -u)
fi

overall_rc=0
missing_tools=()

mark_missing_tool() {
  local tool="$1"
  local reason="$2"
  echo "pre-push: skipping ${reason} (${tool} not found in PATH)." >&2
  missing_tools+=("$tool")
  if [[ "$FAIL_ON_MISSING_TOOLS" == "1" ]]; then
    overall_rc=1
  fi
}

run_check() {
  local label="$1"
  shift
  echo "==> ${label}"
  set +e
  "$@"
  local rc=$?
  set -e
  if [[ $rc -ne 0 ]]; then
    overall_rc=1
    echo "pre-push: ${label} failed." >&2
  fi
}

if command -v rg > /dev/null 2>&1; then
  run_check "workflow Git pin guardrail" tools/check_workflow_git_pins.sh
  run_check "workflow download pin guardrail" tools/check_workflow_download_pins.sh
else
  mark_missing_tool "rg" "workflow pin guardrails"
fi

# shellcheck disable=SC2329 # Invoked indirectly via run_check callback dispatch.
run_clang_format_check() {
  local rc=0
  local f=""
  for f in "$@"; do
    if clang-format -n --Werror "$f" > /dev/null 2>&1; then
      continue
    fi
    if ! diff -u "$f" <(clang-format "$f") > /dev/null; then
      echo "pre-push: formatting issues found in ${f}" >&2
      rc=1
    fi
  done
  return "$rc"
}

if [[ ${#format_files[@]} -gt 0 ]]; then
  if command -v clang-format > /dev/null 2>&1; then
    run_check "clang-format check (${#format_files[@]} file(s))" run_clang_format_check "${format_files[@]}"
  else
    mark_missing_tool "clang-format" "format check"
  fi
fi

if [[ ${#cmake_format_files[@]} -gt 0 ]]; then
  if command -v gersemi > /dev/null 2>&1; then
    run_check "gersemi check (${#cmake_format_files[@]} file(s))" tools/cmake_format_check.sh -- "${cmake_format_files[@]}"
  else
    mark_missing_tool "gersemi" "CMake format check"
  fi
fi

if [[ ${#analysis_tus[@]} -gt 0 ]]; then
  if command -v clang-tidy > /dev/null 2>&1; then
    run_check "clang-tidy (${#analysis_tus[@]} TU(s))" tools/clang_tidy.sh -- "${analysis_tus[@]}"
  else
    mark_missing_tool "clang-tidy" "clang-tidy analysis"
  fi
fi

if [[ ${#cppcheck_sources[@]} -gt 0 ]]; then
  if command -v cppcheck > /dev/null 2>&1; then
    run_check "cppcheck strict (${#cppcheck_sources[@]} TU(s))" tools/cppcheck.sh --strict -- "${cppcheck_sources[@]}"
  else
    mark_missing_tool "cppcheck" "cppcheck analysis"
  fi
fi

if [[ ${#analysis_tus[@]} -gt 0 ]]; then
  if command -v include-what-you-use > /dev/null 2>&1; then
    run_check "IWYU strict (${#analysis_tus[@]} TU(s))" tools/iwyu.sh --strict -- "${analysis_tus[@]}"
  else
    mark_missing_tool "include-what-you-use" "IWYU analysis"
  fi
fi

if [[ ${#analysis_tus[@]} -gt 0 ]]; then
  if command -v gcc > /dev/null 2>&1 && command -v g++ > /dev/null 2>&1; then
    run_check "GCC fanalyzer strict (${#analysis_tus[@]} TU(s))" tools/gcc_fanalyzer.sh --strict -- "${analysis_tus[@]}"
  else
    mark_missing_tool "gcc/g++" "GCC fanalyzer analysis"
  fi
fi

if [[ ${#semgrep_targets[@]} -gt 0 ]]; then
  if command -v semgrep > /dev/null 2>&1; then
    run_check "Semgrep strict (${#semgrep_targets[@]} path(s))" tools/semgrep.sh --strict -- "${semgrep_targets[@]}"
  else
    mark_missing_tool "semgrep" "Semgrep analysis"
  fi
fi

if [[ ${#shell_lint_targets[@]} -gt 0 ]]; then
  if command -v shellcheck > /dev/null 2>&1 && command -v shfmt > /dev/null 2>&1; then
    run_check "shell lint (${#shell_lint_targets[@]} file(s))" tools/shell_lint.sh -- "${shell_lint_targets[@]}"
  else
    mark_missing_tool "shellcheck/shfmt" "shell lint"
  fi
fi

if [[ ${#workflow_lint_targets[@]} -gt 0 ]]; then
  if command -v actionlint > /dev/null 2>&1; then
    run_check "workflow lint (${#workflow_lint_targets[@]} file(s))" tools/workflow_lint.sh -- "${workflow_lint_targets[@]}"
  else
    mark_missing_tool "actionlint" "workflow lint"
  fi
fi

if [[ ${#workflow_security_targets[@]} -gt 0 ]]; then
  if command -v zizmor > /dev/null 2>&1; then
    run_check "zizmor workflow security" tools/zizmor.sh
  else
    mark_missing_tool "zizmor" "workflow security analysis"
  fi
fi

if [[ ${#dependency_scan_targets[@]} -gt 0 ]]; then
  if command -v osv-scanner > /dev/null 2>&1 || command -v docker > /dev/null 2>&1; then
    run_check "OSV dependency scan" tools/osv_scan.sh
  else
    mark_missing_tool "osv-scanner/docker" "OSV dependency scan"
  fi
fi

if command -v lizard > /dev/null 2>&1; then
  run_check "Lizard complexity (src/include)" tools/lizard.sh --strict
else
  mark_missing_tool "lizard" "Lizard complexity analysis"
fi

if [[ "$RUN_SCAN_BUILD" == "1" ]]; then
  if command -v scan-build > /dev/null 2>&1; then
    run_check "scan-build strict (full rebuild)" tools/scan_build.sh --strict
  else
    mark_missing_tool "scan-build" "scan-build analysis"
  fi
else
  echo "pre-push: skipping scan-build full rebuild (set MBE_HOOK_RUN_SCAN_BUILD=1 to enable)."
fi

if [[ ${#missing_tools[@]} -gt 0 ]]; then
  mapfile -t missing_tools < <(printf '%s\n' "${missing_tools[@]}" | sort -u)
  echo "pre-push: missing tools: ${missing_tools[*]}" >&2
  if [[ "$FAIL_ON_MISSING_TOOLS" == "1" ]]; then
    echo "pre-push: failing because MBE_HOOK_FAIL_ON_MISSING_TOOLS=1." >&2
  fi
fi

if [[ $overall_rc -ne 0 ]]; then
  exit 1
fi

exit 0
