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

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

mapfile -t staged_files < <(git diff --cached --name-only --diff-filter=ACMR)
if [[ ${#staged_files[@]} -eq 0 ]]; then
	exit 0
fi

has_staged_match() {
	local pattern="$1"
	for f in "${staged_files[@]}"; do
		if [[ "$f" =~ $pattern ]]; then
			return 0
		fi
	done
	return 1
}

server_route_like_changed=false
if has_staged_match '^server/NeonSprawl\.Server/.*(Api\.cs|Dtos\.cs|Program\.cs)$'; then
	server_route_like_changed=true
fi

if [[ "$server_route_like_changed" == true ]]; then
	if ! has_staged_match '^server/NeonSprawl\.Server\.Tests/'; then
		echo "pre-commit: server route/contract files changed but no server tests staged." >&2
		echo "Add or update tests under server/NeonSprawl.Server.Tests/ before commit." >&2
		exit 1
	fi
	if ! has_staged_match '^bruno/neon-sprawl-server/.*\.bru$'; then
		echo "pre-commit: server route/contract files changed but no Bruno request staged." >&2
		echo "Add/update .bru requests under bruno/neon-sprawl-server/ before commit." >&2
		exit 1
	fi
fi

if has_staged_match '^client/scripts/.*\.gd$'; then
	if ! has_staged_match '^client/test/.*_test\.gd$'; then
		echo "pre-commit: client/scripts .gd changes require test updates in client/test/*_test.gd." >&2
		exit 1
	fi
fi
