#!/bin/bash
# pre-push: block push if lint fails.
set -uo pipefail

if [ -n "${CI:-}" ] || [ -n "${GITHUB_ACTIONS:-}" ]; then
  exit 0
fi

cd "$(git rev-parse --show-toplevel 2>/dev/null || echo .)"

if [ -f ".venv/bin/activate" ]; then
  source .venv/bin/activate
fi

errors=""

# Python lint — apple
if [ -d "apple" ] && command -v ruff &>/dev/null; then
  py_out=$(ruff check apple/ 2>&1)
  if [ $? -ne 0 ]; then
    errors+="=== ruff check apple/ ===\n${py_out}\n\n"
  fi
fi

# Python lint — pine-python
if [ -d "pine-python" ] && command -v ruff &>/dev/null; then
  pyp_out=$(ruff check pine-python/ 2>&1)
  if [ $? -ne 0 ]; then
    errors+="=== ruff check pine-python/ ===\n${pyp_out}\n\n"
  fi
fi

# Go lint
if [ -f "pine-go/go.mod" ] && command -v golangci-lint &>/dev/null; then
  go_out=$(cd pine-go && golangci-lint run ./... 2>&1)
  if [ $? -ne 0 ]; then
    errors+="=== golangci-lint run ./... ===\n${go_out}\n\n"
  fi
fi

# Java lint
if [ -f "pine-java/pom.xml" ] && command -v mvn &>/dev/null; then
  java_out=$(cd pine-java && mvn checkstyle:check -B -q 2>&1)
  if [ $? -ne 0 ]; then
    errors+="=== mvn checkstyle:check ===\n${java_out}\n\n"
  fi
fi

# C++ format
if [ -d "pine-cpp" ] && command -v clang-format &>/dev/null; then
  cpp_out=$(find pine-cpp -type d \( -name 'build' -o -name 'build-*' \) -prune \
    -o -type f \( -name '*.cpp' -o -name '*.hpp' \) -print0 \
    | xargs -0 clang-format --dry-run --Werror 2>&1)
  if [ $? -ne 0 ]; then
    errors+="=== clang-format ===\n${cpp_out}\n\n"
  fi
fi

if [ -n "$errors" ]; then
  echo -e "$errors" >&2
  exit 1
fi

echo "pre-push: all lint checks passed."
exit 0
