#!/bin/sh
#
# 提交前的快速自检。只看本次暂存的文件，保证秒级完成。
#
# 启用方式（仓库根目录执行一次即可）：
#   git config core.hooksPath .githooks
#
# 临时跳过：git commit --no-verify

set -u

red()  { printf '\033[31m%s\033[0m\n' "$1"; }
green(){ printf '\033[32m%s\033[0m\n' "$1"; }

fail=0

# 只取暂存区里存活的文件（排除本次删除的）
staged=$(git diff --cached --name-only --diff-filter=ACMR)
[ -z "$staged" ] && exit 0

staged_php=$(echo "$staged" | grep -E '\.php$' || true)
staged_json=$(echo "$staged" | grep -E '\.json$' || true)

# 1) PHP 语法
if [ -n "$staged_php" ]; then
    for f in $staged_php; do
        [ -f "$f" ] || continue
        if ! php -l "$f" > /dev/null 2>&1; then
            red "语法错误：$f"
            php -l "$f" 2>&1 | sed 's/^/    /'
            fail=1
        fi
    done
fi

# 2) 混入字符检查
#
# 写代码时曾两次把西里尔字母误插进 PHP 源码（如 'ustc' => '...', 后面跟一串西里尔字母）。
# 这类字符在语法上是合法的常量名，php -l 完全查不出来，直到运行时才抛
# "Undefined constant"。中文注释是正常的，所以只拦西里尔/希腊/亚美尼亚这几个
# 与 ASCII 字母外形相近、最容易混进来的区段。
#
# 这里用 PHP 而不是 grep -P：PCRE 只有在 UTF-8 模式下才认 \x{0400} 这种写法，
# 而 grep 是否启用 UTF-8 取决于 locale。git 调用钩子时的 locale 与交互式 shell
# 往往不同，于是同一条命令在手动执行时能命中、在钩子里却静默放过。
# PHP 的 preg 带 /u 修饰符，行为不受环境影响。
if [ -n "$staged_php" ]; then
    for f in $staged_php; do
        [ -f "$f" ] || continue
        hits=$(php -r '
            $src = file_get_contents($argv[1]);
            $bad = [];
            foreach (explode("\n", $src) as $i => $line) {
                if (preg_match("/[\x{0370}-\x{03FF}\x{0400}-\x{04FF}\x{0530}-\x{058F}]/u", $line)) {
                    $bad[] = ($i + 1) . ": " . trim($line);
                }
            }
            echo implode("\n", array_slice($bad, 0, 5));
        ' "$f" 2>/dev/null)
        if [ -n "$hits" ]; then
            red "发现疑似误插入的西里尔/希腊/亚美尼亚字符：$f"
            echo "$hits" | sed 's/^/    /'
            fail=1
        fi
    done
fi

# 2.5) PHP 7.1 语法兼容性
#
# 本项目最低支持 PHP 7.1，而开发机上的 php -l 用的是当前版本的解析器，
# 7.2+ 的语法在那里一路绿灯——上面第 1 步根本拦不住。CI 的低版本 job 能拦，
# 但那是几分钟之后的事，改回来的代价比在这里挡住大得多。
#
# 全量扫描不到一秒，就不做暂存文件筛选了：漏扫一个文件的代价远高于这点开销。
if [ -n "$staged_php" ] && [ -f tests/php71_compat_test.php ]; then
    if ! out=$(php tests/php71_compat_test.php 2>&1); then
        red "PHP 7.1 语法兼容性检查未通过："
        echo "$out" | grep -E '✗|:[0-9]+ ' | head -20 | sed 's/^/    /'
        fail=1
    fi
fi

# 3) JSON 合法性
if [ -n "$staged_json" ]; then
    for f in $staged_json; do
        [ -f "$f" ] || continue
        if ! php -r 'exit(json_decode(file_get_contents($argv[1])) === null && json_last_error() !== JSON_ERROR_NONE ? 1 : 0);' "$f" 2>/dev/null; then
            red "JSON 非法：$f"
            fail=1
        fi
    done
fi

# 4) composer.json 改动时做一次严格校验
if echo "$staged" | grep -q '^composer\.json$'; then
    if command -v composer > /dev/null 2>&1; then
        if ! composer validate --strict --no-check-publish --no-interaction > /tmp/pc-validate.log 2>&1; then
            red "composer.json 严格校验未通过："
            grep -v 'root/super user' /tmp/pc-validate.log | sed 's/^/    /'
            fail=1
        fi
    fi
    # 包名必须与 GitHub 仓库路径一致，否则 Packagist 会拒绝收录。
    #
    # 遍历全部 remote 找 GitHub 地址，而不是只认 origin：本仓库的 origin 指向
    # 本地裸仓库，GitHub 地址挂在另一个名为 github 的 remote 上。
    # 一个 GitHub remote 都没有时直接跳过 —— 那种情况下无从判断预期包名。
    github_url=$(git remote -v 2>/dev/null | grep -i 'github\.com' | head -1 | awk '{print $2}' || true)
    if [ -n "$github_url" ]; then
        expected=$(echo "$github_url" | sed -E 's#^.*github\.com[:/]##; s#\.git$##' | tr '[:upper:]' '[:lower:]')
        declared=$(php -r 'echo json_decode(file_get_contents("composer.json"), true)["name"] ?? "";' 2>/dev/null)
        if [ -n "$expected" ] && [ -n "$declared" ] && [ "$expected" != "$declared" ]; then
            red "composer.json 的 name ($declared) 与 GitHub 仓库路径 ($expected) 不一致，Packagist 将拒绝收录。"
            fail=1
        fi
    fi
fi

if [ "$fail" -ne 0 ]; then
    red "pre-commit 检查未通过，提交已中止。确认无误可用 git commit --no-verify 跳过。"
    exit 1
fi

green "pre-commit 检查通过"
exit 0
