#!/usr/bin/env bash
# Limedoc fmt + lint pre-push gate (app + nested pack/catalog remotes).
set -euo pipefail

# Walk up for limedoc app deno.json (tasks include start:container).
# Fmt uses that config for style. Nested remotes lint with --no-config so the
# app's lint.exclude ("plugins/") does not hide pack sources; ignore generated
# client/vendor trees; exclude require-await (same as app deno.json).
find_limedoc_config() {
	local dir
	dir="$(pwd)"
	while [ "$dir" != "/" ]; do
		if [ -f "$dir/deno.json" ] &&
			grep -q '"start:container"' "$dir/deno.json" 2>/dev/null; then
			printf '%s' "$dir/deno.json"
			return 0
		fi
		dir="$(dirname "$dir")"
	done
	return 1
}

is_app_root() {
	[ -f ./deno.json ] && grep -q '"start:container"' ./deno.json 2>/dev/null
}

FMT_ARGS=()
if CONFIG="$(find_limedoc_config)"; then
	FMT_ARGS=(--config "$CONFIG")
	echo "pre-push: fmt using config $CONFIG"
fi

echo "pre-push: deno fmt --check ."
if ! deno fmt --check "${FMT_ARGS[@]}" .; then
	echo "pre-push: format check failed. Run: deno fmt ${FMT_ARGS[*]:-} ." >&2
	echo "pre-push: then retry git push." >&2
	exit 1
fi

LINT_ARGS=()
if is_app_root; then
	echo "pre-push: deno lint . (app config)"
else
	LINT_ARGS=(
		--no-config
		--rules-exclude=require-await
		--ignore=client/,vendor/,**/vendor/**
	)
	echo "pre-push: deno lint --no-config (nested; ignore client/vendor)"
fi

lint_out="$(mktemp)"
trap 'rm -f "$lint_out"' EXIT
set +e
deno lint "${LINT_ARGS[@]}" . >"$lint_out" 2>&1
lint_status=$?
set -e
if [ "$lint_status" -ne 0 ]; then
	if grep -q 'No target files found' "$lint_out"; then
		echo "pre-push: deno lint skipped (no lintable files)"
	else
		cat "$lint_out" >&2
		echo "pre-push: lint failed. Fix reported issues, then retry git push." >&2
		exit 1
	fi
else
	cat "$lint_out"
fi
