#!/bin/sh
# 提交前钩子：跑 L1 单元测试（229 项，约 4 秒），失败则拒绝提交。
#
# 启用（每人一次，克隆后执行）：git config core.hooksPath .githooks
# 临时跳过：git commit --no-verify
# 关闭：    git config --unset core.hooksPath
#
# 约定：钩子只做「快速、离线、无硬件依赖」的检查；
#       ctest / video_eval / 浸泡属于发布前检查（见 docs/git_workflow.md §5）。

PY=""
for c in python python3 py; do
    if command -v "$c" >/dev/null 2>&1; then
        PY="$c"
        break
    fi
done

if [ -z "$PY" ]; then
    echo "[pre-commit] 未找到 python，跳过单元测试"
    exit 0
fi

if [ ! -d tests ] || [ ! -f pyproject.toml ]; then
    echo "[pre-commit] 不在仓库根目录，跳过单元测试"
    exit 0
fi

LOG="$(mktemp 2>/dev/null || echo /tmp/portcv_precommit.log)"

echo "[pre-commit] 运行 tests/ 单元测试 ..."
if ! "$PY" -m unittest discover -s tests -q >"$LOG" 2>&1; then
    echo "[pre-commit] 单元测试失败，提交被拒绝："
    tail -n 40 "$LOG"
    echo "[pre-commit] 修复后重试；确认要绕过：git commit --no-verify"
    exit 1
fi

echo "[pre-commit] 单元测试通过"
exit 0
