#!/usr/bin/env bash
# =============================================================================
# Linux Patch Manager — Pre-Commit Hook
# =============================================================================
# Auto-formats Rust code and runs frontend type check before each commit.
# Prevents CI format-check failures by ensuring code is always formatted.
# Install: ./scripts/git-hooks/install.sh
# =============================================================================

set -euo pipefail

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

# ── Rust auto-format ──────────────────────────────────────────────────────────
if [[ -f "${REPO_ROOT}/Cargo.toml" ]]; then
    echo "[pre-commit] Running cargo fmt --all ..."
    cargo fmt --all --manifest-path "${REPO_ROOT}/Cargo.toml" 2>/dev/null

    # Re-stage any files that cargo fmt reformatted (including previously unstaged)
    STAGED_RS=$(git diff --name-only --diff-filter=ACM -- '*.rs')
    if [[ -n "${STAGED_RS}" ]]; then
        git add ${STAGED_RS}
    fi
fi

# ── Frontend type check ─────────────────────────────────────────────────────
if [[ -f "${REPO_ROOT}/frontend/package.json" ]]; then
    echo "[pre-commit] Running TypeScript type check ..."
    cd "${REPO_ROOT}/frontend"
    npx tsc --noEmit 2>/dev/null
fi

echo "[pre-commit] All checks passed ✓"
