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

repo_root="$(git rev-parse --show-toplevel)"
cd "$repo_root"

echo "pre-push: checking for a clean working tree"
if [[ -n "$(git status --porcelain)" ]]; then
	echo "pre-push: refuse to push — working tree is not clean. Commit, stash, or remove changes first:" >&2
	git status --short >&2
	exit 1
fi

gdlint_bin=""
gdformat_bin=""

if [[ -x "$repo_root/.venv-gd/bin/gdlint" ]]; then
	gdlint_bin="$repo_root/.venv-gd/bin/gdlint"
elif [[ -x "$repo_root/.venv-gd/Scripts/gdlint.exe" ]]; then
	gdlint_bin="$repo_root/.venv-gd/Scripts/gdlint.exe"
elif command -v gdlint >/dev/null 2>&1; then
	gdlint_bin="$(command -v gdlint)"
fi

if [[ -x "$repo_root/.venv-gd/bin/gdformat" ]]; then
	gdformat_bin="$repo_root/.venv-gd/bin/gdformat"
elif [[ -x "$repo_root/.venv-gd/Scripts/gdformat.exe" ]]; then
	gdformat_bin="$repo_root/.venv-gd/Scripts/gdformat.exe"
elif command -v gdformat >/dev/null 2>&1; then
	gdformat_bin="$(command -v gdformat)"
fi

if [[ -z "$gdlint_bin" || -z "$gdformat_bin" ]]; then
	echo "pre-push: missing gdtoolkit commands (gdlint/gdformat)." >&2
	echo "Install locally with:" >&2
	echo "  python3 -m venv .venv-gd" >&2
	echo "  .venv-gd/bin/pip install \"gdtoolkit==4.5.0\"" >&2
	exit 1
fi

echo "pre-push: running gdlint on client/scripts and client/test"
"$gdlint_bin" client/scripts client/test

echo "pre-push: running gdformat --check on client/scripts and client/test"
"$gdformat_bin" --check client/scripts client/test
