#!/bin/sh
# Pre-commit hook: run cargo fmt check, clippy, and gitignore guard
# Install: git config core.hooksPath .githooks

set -e

# Guard: prevent files that should stay untracked from being committed
FORBIDDEN_FILES="CLAUDE.md"
for f in $FORBIDDEN_FILES; do
    if git diff --cached --name-only | grep -qx "$f"; then
        echo "ERROR: '$f' is staged for commit but should not be tracked."
        echo "Run: git rm --cached $f"
        exit 1
    fi
done

echo "Running cargo fmt --check..."
cargo fmt --check
if [ $? -ne 0 ]; then
    echo "cargo fmt check failed. Run 'cargo fmt' to fix."
    exit 1
fi

echo "Running cargo clippy..."
cargo clippy -- -D warnings
if [ $? -ne 0 ]; then
    echo "cargo clippy failed. Fix warnings before committing."
    exit 1
fi

# Frontend checks (only if frontend files are staged)
FRONTEND_DIR="crates/tmai-app/web"
if git diff --cached --name-only | grep -q "^${FRONTEND_DIR}/src/"; then
    echo "Running frontend checks..."
    if ! command -v pnpm >/dev/null 2>&1; then
        echo "ERROR: pnpm not found. Install pnpm to run frontend checks."
        exit 1
    fi
    if [ ! -d "$FRONTEND_DIR/node_modules" ]; then
        echo "node_modules not found, running pnpm install..."
        (cd "$FRONTEND_DIR" && pnpm install --frozen-lockfile)
    fi
    (cd "$FRONTEND_DIR" && npx biome check src/ && npx tsc --noEmit)
    if [ $? -ne 0 ]; then
        echo "Frontend check failed. Fix lint/type errors before committing."
        exit 1
    fi
fi
