#!/usr/bin/env bash
# v1.9.12 随手批 —— 检查14 证1 谓词【隔离复算】(唯该面 · 非整门)
# 谓词逐字取自 scripts/verify_release.sh:2751-2807(本席一手抄录 · 未改)
set -uo pipefail
ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
cd "$ROOT" || exit 1

CHECK14_SCAN_PATHS=(src crates scripts .github .xuanwu install.sh Makefile deny.toml rust-toolchain.toml Cargo.toml Cargo.lock Cargo.lock.sha256 clippy.toml rustfmt.toml typos.toml .config/nextest.toml .gitleaks.toml)
gate_excludes=(--exclude=verify_release.sh --exclude=release_gates_v1210.sh)

# 名册(自 verify_release.sh 哨符区间实抽 · 非手抄)
REG="$(awk '/>>> CHECK14_REGISTRY_BEGIN/,/<<< CHECK14_REGISTRY_END/' scripts/verify_release.sh)"
mapfile -t lock_tests < <(printf '%s\n' "$REG" | sed -n '/local lock_tests=(/,/^ *)/p' | grep -oE '"[^"]+"' | tr -d '"')

c14_guard_rel="$(bash scripts/tests/v143_gates.sh --print-active-guard 2>/dev/null)"
c14_guard_rel="${c14_guard_rel#"$ROOT"/}"

echo "名册项数 = ${#lock_tests[@]}"
echo "现役世代档 = $c14_guard_rel"
missing=(); onlycomment=(); notactive=()
for t in "${lock_tests[@]}"; do
    hit_lines="$(grep -rn "${gate_excludes[@]}" "$t" "${CHECK14_SCAN_PATHS[@]}" 2>/dev/null || true)"
    if [[ -z "$hit_lines" ]]; then missing+=("$t"); continue; fi
    code_ok=0
    while IFS= read -r line; do
        stripped="${line#*:*:}"; stripped="${stripped%%#*}"; stripped="${stripped%%//*}"
        [[ -n "${stripped//[[:space:]]/}" ]] && { code_ok=1; break; }
    done <<< "$hit_lines"
    if [[ "$code_ok" -eq 0 ]]; then onlycomment+=("$t"); continue; fi
    if [[ "$t" =~ ^v1[0-9]+_ && -n "$c14_guard_rel" ]]; then
        g_hit=0
        while IFS= read -r g_line; do
            [[ "$g_line" == "$c14_guard_rel:"* ]] || continue
            g_str="${g_line#*:*:}"; g_str="${g_str%%#*}"; g_str="${g_str%%//*}"
            [[ -n "${g_str//[[:space:]]/}" ]] && { g_hit=1; break; }
        done <<< "$hit_lines"
        [[ "$g_hit" -eq 0 ]] && notactive+=("$t")
    fi
done
echo "missing(未命中)      = ${#missing[@]} ${missing[*]:-}"
echo "onlycomment(仅注释)  = ${#onlycomment[@]} ${onlycomment[*]:-}"
echo "notactive(不在现役档)= ${#notactive[@]} ${notactive[*]:-}"
rc=0
[[ ${#missing[@]} -eq 0 && ${#onlycomment[@]} -eq 0 && ${#notactive[@]} -eq 0 ]] || rc=1
echo "CHECK14_LEG1_RC=$rc"
exit $rc