#!/bin/sh
# RefineID Windows commit gate.
#
# Enforces the local format, lint, and unit-test quality gate before committing.
# Enable it once per clone with:
#
#     git config core.hooksPath .githooks
#
# Formatting, clippy lints (both host and Windows cross-target), and unit tests
# run on commit so that bad quality code is caught before pushing to GitHub.
# Markdown links must stay inside the repository: a link into a sibling
# checkout resolves only on a developer's disk and is broken on GitHub.

set -e

if git ls-files | grep -i -E '(^|/)WHATSUP\.md$' >/dev/null; then
    echo "pre-commit: error: WHATSUP.md files are forbidden."
    exit 1
fi

# Classify before dependency refresh or any compiler invocation.
if python3 "$(git rev-parse --show-toplevel)/scripts/DocumentationGate.py" commit; then
    exit 0
else
    scope_status=$?
    if [ "$scope_status" -ne 1 ]; then
        exit "$scope_status"
    fi
fi



# Stamp the workspace version to the UTC day when the day changed. The
# manifest carries CalVer YY.M.D; the apps and packages add the time bucket
# at build.
root=$(git rev-parse --show-toplevel)

# RefineID's own crates are never pinned: every commit builds the head of
# refineid-core main. Without the network the lock file keeps its core
# revision, and the daily track-core-main job moves it later. This comes
# first, so a moved core counts as a code-level change below.
if cargo update --quiet --package refineid-rapp; then
    git add "$root/Cargo.lock"
else
    echo "pre-commit: core main not reachable; the lock file keeps its core revision" >&2
fi

# The workspace version names the UTC day of the last code-level change.
# A commit that touches only documentation, workflows or hooks keeps it.
if git diff --cached --name-only | grep -q -v -E '^(\.github/|\.githooks/|doc/|docs/)|\.md$|^LICENSE|^\.gitignore$|^\.editorconfig$'; then
    stamped=$("$root/scripts/version-stamp.sh")
    if [ -n "$stamped" ]; then
        echo "pre-commit: $stamped"
        git add "$root/Cargo.toml" "$root/Cargo.lock"
    fi
fi

echo "pre-commit: markdown links stay inside the repository"
link_open='](' # markdown inline link opener preceding the target
parent_dir='../'
escaping=$(git ls-files -z -- '*.md' | xargs -0 awk \
    -v open_len="${#link_open}" -v parent_len="${#parent_dir}" '
    FNR == 1 { depth = gsub("/", "/", FILENAME) }
    {
        line = $0
        while (match(line, /\]\((\.\.\/)+/)) {
            climb = (RLENGTH - open_len) / parent_len
            if (climb > depth) {
                target = substr(line, RSTART + open_len)
                sub(/\).*$/, "", target)
                print FILENAME ":" FNR ": " target
            }
            line = substr(line, RSTART + RLENGTH)
        }
    }')
if [ -n "$escaping" ]; then
    echo "pre-commit: error: relative links leave the repository; link the GitHub URL instead:" >&2
    echo "$escaping" >&2
    exit 1
fi

python3 -B scripts/TestDocumentationGate.py

echo "pre-commit: cargo fmt --all --check"
cargo fmt --all --check

echo "pre-commit: magic-number policy"
RUSTFLAGS="${RUSTFLAGS:+${RUSTFLAGS} }-D warnings" cargo run -q -p xtask -- check-magic-numbers --staged

echo "pre-commit: dotnet csharpier check"
dotnet tool restore >/dev/null
dotnet csharpier check .

echo "pre-commit: cargo clippy (native host)"
cargo clippy --workspace --all-targets -- -D warnings

if rustup target list --installed | grep -q "x86_64-pc-windows-msvc"; then
    echo "pre-commit: cargo clippy (x86_64-pc-windows-msvc)"
    cargo clippy --target x86_64-pc-windows-msvc --workspace --all-targets -- -D warnings
fi

echo "pre-commit: cargo test --workspace"
RUSTFLAGS="${RUSTFLAGS:+${RUSTFLAGS} }-D warnings" cargo test --workspace

echo "pre-commit: ok (all quality checks passed)"
