#!/usr/bin/env bash
set -euo pipefail

cd "$(git rev-parse --show-toplevel)"

push_lines="$(cat)"
while read -r local_ref local_sha remote_ref remote_sha; do
    if [ "$local_sha" = "0000000000000000000000000000000000000000" ]; then
        echo "[pre-push] 分支删除推送，跳过测试"
        exit 0
    fi
done <<< "$push_lines"

if [ "${SKIP_TESTS:-0}" = "1" ]; then
    echo "[pre-push] SKIP_TESTS=1，跳过测试"
    exit 0
fi

python_files=()
while read -r local_ref local_sha remote_ref remote_sha; do
    [ -z "$local_sha" ] && continue
    if [ "$local_sha" = "0000000000000000000000000000000000000000" ]; then
        continue
    fi
    if [ "$remote_sha" = "0000000000000000000000000000000000000000" ]; then
        changed_paths="$(git diff-tree --no-commit-id --name-only -r --root "$local_sha" -- '*.py')"
    else
        changed_paths="$(git diff --name-only "$remote_sha..$local_sha" -- '*.py')"
    fi
    while IFS= read -r path; do
        [ -n "$path" ] && python_files+=("$path")
    done <<< "$changed_paths"
done <<< "$push_lines"

if [ "${#python_files[@]}" -gt 0 ]; then
    echo "[pre-push] 检查 Python 格式..."
    uv run --group dev ruff format --check "${python_files[@]}"
    echo "[pre-push] Python 格式通过"
fi

if [ "${TYPECHECK:-0}" = "1" ]; then
    echo "[pre-push] 运行 Pyright 类型检查..."
    uv run --group dev pyright
    echo "[pre-push] Pyright 通过"
fi

echo "[pre-push] 运行 pytest..."
./dev.sh test -q
echo "[pre-push] pytest 通过"
