#!/usr/bin/env bash
# Refuse commits that would put game content into git (D-005, CLAUDE.md hard rules).
#
# Enabled per clone with:   git config core.hooksPath tools/git-hooks
# (tools/preflight.py --fix does this). Runs under Git Bash on Windows.
#
# Checks every staged file for:
#   1. protected paths (game/, reference/, src/recomp/gen/, analysis/, runs/, ghidra/)
#   2. game/asset/disc file types
#   3. size over 5 MB (nothing we write by hand is that big)
#   4. content: an XBE header, or the recompiler's generated-code markers
#
# Never bypass this with --no-verify. If it blocks something that is genuinely
# ours, rename/move it or extend the rules here in a reviewed commit.

MAX_BYTES=5242880
fail=0

block() {
    echo "pre-commit: BLOCKED $1" >&2
    echo "            reason: $2" >&2
    fail=1
}

# NUL-separated so names with spaces survive.
git diff --cached --name-only --diff-filter=ACMRT -z | {
while IFS= read -r -d '' f; do
    lower=$(printf '%s' "$f" | tr '[:upper:]' '[:lower:]')

    case "$lower" in
        game/.keep|reference/.keep) ;;
        game/*|reference/*|src/recomp/gen/*|analysis/*|runs/*|ghidra/*|*/xbe_flat.bin)
            block "$f" "protected path (game data, references, generated C or analysis output)"; continue ;;
    esac

    case "$lower" in
        *.xbe|*.iso|*.xiso|*.img|*.bin|*.gdf|*.pak|*.toc|*.bik|*.xmv|*.wma|*.wav|*.xwb|*.xpr|\
        *.dds|*.tga|*.bmp|*.png|*.jpg|*.jpeg|*.mp4|*.mkv|*.avi|*.webm|*.pdf|*.7z|*.zip|*.rar|\
        *.gz|*.dmp|*.gpr|*.obj|*.lib|*.exe|*.pdb|*.dll)
            block "$f" "file type that is game content, a capture, a binary or an archive"; continue ;;
    esac

    size=$(git cat-file -s ":$f" 2>/dev/null || echo 0)
    if [ "$size" -gt "$MAX_BYTES" ]; then
        block "$f" "larger than 5 MB ($size bytes)"; continue
    fi

    magic=$(git cat-file blob ":$f" 2>/dev/null | head -c 4)
    if [ "$magic" = "XBEH" ]; then
        block "$f" "content is an Xbox executable (XBEH header)"; continue
    fi

    # This hook quotes the markers it looks for, so skip the marker test for itself.
    if [ "$lower" != "tools/git-hooks/pre-commit" ] && \
       git cat-file blob ":$f" 2>/dev/null | head -c 65536 | \
       grep -q -e 'RECOMP_GENERATED_CODE' -e 'auto-generated by tools/recomp' -e 'Recompiled Function Declarations'; then
        block "$f" "content is recompiler output (generated C)"; continue
    fi

done
# The pipe runs this block in a subshell, so hand the verdict out as the exit code.
exit "$fail"
}
fail=$?

if [ "$fail" -ne 0 ]; then
    echo "" >&2
    echo "Commit refused. Unstage the files above (git restore --staged <file>)." >&2
    exit 1
fi
exit 0
