#!/bin/sh
set -eu

# Local quality gate for commits. Keep this aligned with CI and with the
# embedded WebUI build so warnings are caught before a push reaches CI.

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

WARNING_PATTERN='(^|[^[:alpha:]])warn(ing|ings)?([^[:alpha:]]|$)|^\(!\)'

section() {
    printf '\n==> %s\n' "$1"
}

run() {
    label="$1"
    shift
    section "$label"
    "$@"
}

run_no_warnings() {
    label="$1"
    shift
    section "$label"

    output_file="$(mktemp "${TMPDIR:-/tmp}/daat-locus-hook.XXXXXX")"
    set +e
    "$@" >"$output_file" 2>&1
    status="$?"
    set -e

    cat "$output_file"

    if [ "$status" -ne 0 ]; then
        rm -f "$output_file"
        printf '\n%s failed with exit status %s.\n' "$label" "$status" >&2
        exit "$status"
    fi

    if grep -Eiq "$WARNING_PATTERN" "$output_file"; then
        printf '\n%s emitted warning-like output; failing pre-commit hook.\n' "$label" >&2
        printf 'Matched warning lines:\n' >&2
        grep -Ein "$WARNING_PATTERN" "$output_file" >&2 || true
        rm -f "$output_file"
        exit 1
    fi

    rm -f "$output_file"
}

run "Rust formatting" cargo fmt --all -- --check
run_no_warnings "Rust warnings" env RUSTFLAGS="${RUSTFLAGS:+$RUSTFLAGS }-D warnings" cargo check --locked --all-targets
run "Rust clippy" cargo clippy --locked --all-targets -- -D warnings

if [ ! -f webui/package.json ]; then
    printf 'webui/package.json not found; cannot check WebUI warnings.\n' >&2
    exit 1
fi

if command -v corepack >/dev/null 2>&1; then
    (
        cd webui
        run_no_warnings "WebUI warnings" corepack yarn build
    )
elif command -v yarn >/dev/null 2>&1; then
    (
        cd webui
        run_no_warnings "WebUI warnings" yarn build
    )
else
    printf 'Neither corepack nor yarn is available; cannot check WebUI warnings.\n' >&2
    exit 1
fi

printf '\nPre-commit quality checks passed.\n'
