#!/usr/bin/env bash
# Pre-push gate for repository hygiene, deterministic cross-language contracts,
# validation-registry integrity, and every host-compatible Cargo workspace.
#
# Enable once per clone:   git config core.hooksPath .githooks
# Bypass (discouraged):    git push --no-verify
set -euo pipefail
repo_root="$(git rev-parse --show-toplevel)"

pushed_tips=()
pushed_updates=()
while read -r _local_ref local_sha _remote_ref _remote_sha; do
    if [ "${local_sha}" != "0000000000000000000000000000000000000000" ]; then
        pushed_tips+=("${local_sha}")
        pushed_updates+=(--update "${local_sha}" "${_remote_sha}")
    fi
done

if [ "${#pushed_tips[@]}" -gt 0 ]; then
    if ! python3 "${repo_root}/validation/hygiene/no-personal-paths.py" "${pushed_tips[@]}"; then
        echo ""
        echo "✗ push blocked by the personal-path gate (see above)."
        echo "  scrub the offending path or extend the gate's allowlist deliberately."
        exit 1
    fi
fi

if ! bash "${repo_root}/validation/hygiene/fmt-docs.sh"; then
    echo ""
    echo "✗ push blocked by the hygiene gate (see above)."
    echo "  fix formatting: cargo fmt --all   (and resolve any doc-link errors)"
    exit 1
fi

if ! "${repo_root}/tools/prns" run release.host-sdk.versions \
    || ! "${repo_root}/tools/prns" run release.host-sdk.distribution.check \
    || ! "${repo_root}/tools/prns" run repo.host-contract.check; then
    echo ""
    echo "✗ push blocked by the host SDK contract gate (see above)."
    echo "  synchronize release versions, package projections, and generated ABI artifacts."
    exit 1
fi

if ! python3 "${repo_root}/validation/run.py" verify; then
    echo ""
    echo "✗ push blocked by the validation registry gate (see above)."
    echo "  update validation/manifest.toml alongside the files and suites it tracks."
    exit 1
fi

if ! "${repo_root}/tools/prns" repo cargo-check; then
    echo ""
    echo "✗ push blocked by the repository Cargo check (see above)."
    echo "  fix every failed workspace before retrying the push."
    exit 1
fi

if [ "${#pushed_updates[@]}" -gt 0 ]; then
    if ! python3 "${repo_root}/validation/hygiene/pre-push-ci-parity.py" "${pushed_updates[@]}"; then
        echo ""
        echo "✗ push blocked by a diff-selected CI parity check (see above)."
        echo "  fix the failing Clippy, host binding, or RustSec lane before retrying."
        exit 1
    fi
fi
