#!/usr/bin/env python3
"""
Pre-commit 钩子入口：放置校验 + .temp 生命周期 + 敏感信息检测 + 模式V2质量 + 并发模块安全八维检查
在 git commit 前自动扫描高风险问题并阻断提交。

检查链路（按快速失败原则排序，前置检查更快且面向仓库整体状态）：
  1. 关键配置文件放置校验（受管文件被错误放置到根目录时阻塞）
  2. .temp/ 临时文件生命周期检查（只读，超 30 天内容阻塞提交）
  3. 敏感信息检测（密码/密钥/Token 等）
  4. 模式文档V2质量检查（创新类模式必须含失败案例+反目标用户分析）
  5. Ruff lint（仅扫描启用了 [tool.ruff] 的应用中被暂存的 .py 文件）
  6. 并发模块安全八维检查（超时/幂等/边界/防御/配置/国际化/死锁/泄漏）

使用方式：
  1. 通过 install-hooks.py 自动安装（推荐）
  2. 手动复制本文件到 .git/hooks/pre-commit 并添加执行权限

环境变量控制：
  文件放置校验：
    FILE_PLACEMENT_CHECK_SKIP=1   完全跳过文件放置校验
    SKIP=file-placement-check     同上
  .temp 生命周期检查：
    TEMP_LIFECYCLE_CHECK_SKIP=1   完全跳过 .temp 生命周期检查
    SKIP=temp-lifecycle-check     同上
  敏感信息检测：
    SENSITIVE_CHECK_SKIP=1     完全跳过敏感信息检查
    SENSITIVE_CHECK_WARN_ONLY=1  检测高风险但只警告不阻断（紧急修复用）
    SKIP=sensitive-info-check  同上（兼容 pre-commit 框架习惯）
  模式质量V2检查：
    PATTERN_QUALITY_CHECK_SKIP=1 完全跳过模式V2质量检查
    SKIP=pattern-quality-check   同上
  Ruff lint：
    RUFF_CHECK_SKIP=1             完全跳过 Ruff 检查
    SKIP=ruff-check               同上
    RUFF_BIN=/path/to/ruff        指定 ruff 可执行文件
    RUFF_CHECK_REQUIRED=1         本机找不到 ruff 时阻断提交（CI 用）
  并发安全检查：
    CONCURRENT_CHECK_SKIP=1       完全跳过并发安全检查
    CONCURRENT_CHECK_WARN_ONLY=1  检测到错误只警告不阻断
    SKIP=concurrent-safety-check  同上
    CONCURRENT_CHECK_DIM=TIMEOUT  仅检查指定维度

Git 原生方式：
  git commit --no-verify     跳过所有钩子（不推荐，会跳过其他检查）
"""


# 版本校验：导入共享库
import sys as _sys
from pathlib import Path as _Path
_lib_parent = _Path(__file__).resolve().parent
while not (_lib_parent / "lib").is_dir():
    _lib_parent = _lib_parent.parent
_sys.path.insert(0, str(_lib_parent / "lib"))

from python310_version_check import enforce_python310

enforce_python310()

import os
import subprocess
import sys
from pathlib import Path


def _env_truthy(name: str) -> bool:
    val = os.environ.get(name, "").strip().lower()
    return val in ("1", "true", "yes", "on")


def _skip_requested() -> tuple[bool, str]:
    if _env_truthy("SENSITIVE_CHECK_SKIP"):
        return True, "SENSITIVE_CHECK_SKIP=1"
    skip_env = os.environ.get("SKIP", "").strip().lower()
    if "sensitive-info" in skip_env or "sensitive_check" in skip_env:
        return True, f"SKIP={os.environ.get('SKIP', '')}"
    return False, ""


def _warn_only() -> bool:
    if _env_truthy("SENSITIVE_CHECK_WARN_ONLY"):
        return True
    skip_env = os.environ.get("SKIP", "").strip().lower()
    return "sensitive-info-warn" in skip_env


def _skip_file_placement() -> tuple[bool, str]:
    """文件放置校验是否被环境变量跳过。"""
    if _env_truthy("FILE_PLACEMENT_CHECK_SKIP"):
        return True, "FILE_PLACEMENT_CHECK_SKIP=1"
    skip_env = os.environ.get("SKIP", "").strip().lower()
    if "file-placement" in skip_env or "file_placement" in skip_env:
        return True, f"SKIP={os.environ.get('SKIP', '')}"
    return False, ""


def _skip_temp_lifecycle() -> tuple[bool, str]:
    """.temp 生命周期检查是否被环境变量跳过。"""
    if _env_truthy("TEMP_LIFECYCLE_CHECK_SKIP"):
        return True, "TEMP_LIFECYCLE_CHECK_SKIP=1"
    skip_env = os.environ.get("SKIP", "").strip().lower()
    if "temp-lifecycle" in skip_env or "temp_lifecycle" in skip_env:
        return True, f"SKIP={os.environ.get('SKIP', '')}"
    return False, ""


def find_project_root() -> Path:
    result = subprocess.run(
        ["git", "rev-parse", "--show-toplevel"],
        capture_output=True, text=True,
    )
    if result.returncode != 0:
        return Path(__file__).resolve().parent.parent.parent
    return Path(result.stdout.strip())


def get_staged_files() -> list[Path]:
    result = subprocess.run(
        ["git", "diff", "--cached", "--name-only", "--diff-filter=ACM"],
        capture_output=True, text=True,
    )
    if result.returncode != 0:
        return []
    files = []
    for line in result.stdout.strip().splitlines():
        line = line.strip()
        if line:
            files.append(Path(line))
    return files


def _run_file_placement_check(project_root: Path, scripts_dir: Path) -> int:
    """关键配置文件放置校验：错误放置时阻塞提交并显示修复指引。

    检查仓库整体状态（与暂存文件无关），受管文件出现在根目录即阻塞。
    """
    skip, skip_reason = _skip_file_placement()
    print("=" * 60)
    print("📁 关键配置文件放置校验 (Pre-commit Hook)")
    print("=" * 60)
    if skip:
        print(f"\n⚠️  检测到 {skip_reason}，已跳过文件放置校验。")
        print()
        return 0

    if str(scripts_dir) not in sys.path:
        sys.path.insert(0, str(scripts_dir))

    try:
        from lib.checks.file_placement import run_check
    except ImportError as exc:
        print(f"\n⚠️  无法加载放置校验模块，跳过: {exc}")
        print()
        return 0

    result = run_check(project_root)
    if result.passed:
        print("✅ 所有受管关键文件均在正确位置（.agents/scripts/）")
        print()
        return 0

    print(f"❌ 检测到 {result.error_count} 项错误放置，提交已阻断！")
    print("-" * 60)
    for err in result.errors:
        print(f"  {err}")
    print("\n💡 修复方法（在项目根目录执行）:")
    for err in result.errors:
        if "| 修复: " in err:
            fix_cmd = err.split("| 修复: ", 1)[1]
            print(f"  {fix_cmd}")
    print("\n🔓 临时跳过方式（仅限紧急情况）:")
    print("  FILE_PLACEMENT_CHECK_SKIP=1 git commit")
    print("  git commit --no-verify  (跳过所有钩子，最不推荐)")
    print("=" * 60)
    return 1


def _run_temp_lifecycle_check(project_root: Path, scripts_dir: Path) -> int:
    """.temp/ 生命周期检查（只读）：超 30 天内容阻塞提交并提示运行 --clean。

    采用 CI 错误阈值（>30 天阻塞），14-30 天仅提示不阻塞。
    """
    skip, skip_reason = _skip_temp_lifecycle()
    print("=" * 60)
    print("🕒 .temp/ 生命周期检查 (Pre-commit Hook, 只读)")
    print("=" * 60)
    if skip:
        print(f"\n⚠️  检测到 {skip_reason}，已跳过 .temp 生命周期检查。")
        print()
        return 0

    if str(scripts_dir) not in sys.path:
        sys.path.insert(0, str(scripts_dir))

    try:
        from lib.checks.temp_lifecycle import run_precommit_check
    except ImportError as exc:
        print(f"\n⚠️  无法加载 .temp 生命周期检查模块，跳过: {exc}")
        print()
        return 0

    return run_precommit_check(project_root)


def _run_sensitive_check(project_root: Path, scripts_dir: Path, staged_files: list[Path]) -> int:
    skip, skip_reason = _skip_requested()
    warn_only_mode = _warn_only()

    if skip:
        print("=" * 60)
        print("🔒 敏感信息检测 (Pre-commit Hook)")
        print("=" * 60)
        print(f"\n⚠️  检测到 {skip_reason}，已跳过敏感信息检查。")
        print("   请确保本次提交不包含真实敏感信息！")
        print()
        return 0

    if str(scripts_dir) not in sys.path:
        sys.path.insert(0, str(scripts_dir))

    print("=" * 60)
    print("🔒 敏感信息检测 (Pre-commit Hook)")
    if warn_only_mode:
        print("   [警告模式] 检测到高风险仅警告，不阻断提交")
    print("=" * 60)

    if not staged_files:
        return 0

    print(f"\n📋 待提交文件: {len(staged_files)} 个")
    for f in staged_files[:5]:
        print(f"   - {f}")
    if len(staged_files) > 5:
        print(f"   ... 及其他 {len(staged_files) - 5} 个文件")

    try:
        from lib.checks.sensitive_info import (
            scan_file, SEVERITY_HIGH, SEVERITY_MEDIUM,
            SUPPORTED_EXTENSIONS, FILE_EXCLUDE_PATTERNS, DEFAULT_EXCLUDE_DIRS,
        )
    except ImportError:
        print("\n⚠️  无法加载检测模块，回退到 CLI 扫描...")
        check_script = scripts_dir / "check-sensitive-info.py"
        if check_script.exists():
            if warn_only_mode:
                result = subprocess.run(
                    [sys.executable, str(check_script)],
                    cwd=str(scripts_dir),
                )
                return 0
            else:
                result = subprocess.run(
                    [sys.executable, str(check_script), "--only-severity", "high"],
                    cwd=str(scripts_dir),
                )
                return result.returncode
        print("❌ 无法找到敏感信息检测脚本，请确认 .agents/scripts/ 完整")
        return 1

    high_findings: list[tuple[Path, object]] = []
    medium_findings: list[tuple[Path, object]] = []

    print("\n🔍 正在扫描暂存文件中的敏感信息...")
    skipped_by_dir = 0
    for rel_path in staged_files:
        abs_path = project_root / rel_path
        if not abs_path.exists():
            continue
        # 目录级排除必须与 CLI 行为一致：DEFAULT_EXCLUDE_DIRS 已排除
        # vendor/external/node_modules 等第三方产物目录，钩子逐文件扫描时
        # 若不应用同一份排除表，会把第三方压缩包里的常量（API 路由路径、
        # 第三方内置 AppID 等）误判成敏感信息并永久阻断提交。
        if any(part in DEFAULT_EXCLUDE_DIRS for part in rel_path.parts[:-1]):
            skipped_by_dir += 1
            continue
        if abs_path.name in FILE_EXCLUDE_PATTERNS:
            continue
        if abs_path.suffix.lower() not in SUPPORTED_EXTENSIONS:
            continue
        try:
            findings = scan_file(abs_path)
            for finding in findings:
                if finding.severity == SEVERITY_HIGH:
                    high_findings.append((rel_path, finding))
                elif finding.severity == SEVERITY_MEDIUM:
                    medium_findings.append((rel_path, finding))
        except (OSError, UnicodeDecodeError):
            continue

    if skipped_by_dir:
        print(f"   （按 DEFAULT_EXCLUDE_DIRS 跳过第三方产物目录中的 {skipped_by_dir} 个文件）")
    print()

    if medium_findings:
        print(f"⚠️  检测到 {len(medium_findings)} 项中风险敏感信息（警告，不阻断提交）:")
        print("-" * 60)
        current_file = None
        for rel_path, f in medium_findings:
            if str(rel_path) != current_file:
                print(f"\n  📄 {rel_path}:")
                current_file = str(rel_path)
            match_preview = f.match[:60] + ("..." if len(f.match) > 60 else "")
            print(f"     L{f.line} ⚠ {f.rule_name}: {match_preview}")
        print()

    if high_findings:
        if warn_only_mode:
            print(f"⚠️  检测到 {len(high_findings)} 项高风险敏感信息（警告模式，不阻断）:")
        else:
            print(f"❌ 检测到 {len(high_findings)} 项高风险敏感信息，提交已阻断！")
        print("-" * 60)
        current_file = None
        for rel_path, f in high_findings:
            if str(rel_path) != current_file:
                print(f"\n  📄 {rel_path}:")
                current_file = str(rel_path)
            match_preview = f.match[:60] + ("..." if len(f.match) > 60 else "")
            fixable = "[可自动修复]" if f.fixable else "[需人工处理]"
            icon = "⚠" if warn_only_mode else "✗"
            print(f"     L{f.line} {icon} {f.rule_name} {fixable}")
            print(f"       匹配: {match_preview}")
            print(f"       建议: {f.suggestion}")

        if warn_only_mode:
            print("\n" + "=" * 60)
            print("⚠️  当前为警告模式，提交将继续。请务必处理上述高风险项！")
            print("=" * 60)
            return 0

        print("\n" + "=" * 60)
        print("💡 修复方法:")
        print("  1. 自动修复: python .agents/scripts/check-sensitive-info.py --fix")
        print("  2. 手动修复: 按上述建议替换敏感信息")
        print("  3. 示例数据: 在代码行尾添加 # nosec 标记（仅限示例/测试数据）")
        print("")
        print("🔓 临时跳过方式（仅限紧急情况）:")
        print("  4. 仅跳过敏感信息检查: SENSITIVE_CHECK_SKIP=1 git commit")
        print("  5. 只警告不阻断: SENSITIVE_CHECK_WARN_ONLY=1 git commit")
        print("  6. 跳过所有钩子: git commit --no-verify  (最不推荐！)")
        print("=" * 60)
        return 1

    if medium_findings:
        print("✅ 未检测到高风险敏感信息。建议处理上述中风险项后再提交。")
        print("   可运行: python .agents/scripts/check-sensitive-info.py --fix 自动修复")
        print()
        return 0

    print("✅ 未检测到敏感信息。")
    print()
    return 0


def _run_pattern_quality_check(project_root: Path, scripts_dir: Path, staged_files: list[Path]) -> int:
    """模式文档V2质量检查：创新/跨领域类模式必须包含失败案例+反目标用户分析。

    仅检查暂存中被修改的模式文档（.md文件在patterns/目录下）。
    """
    skip = _env_truthy("PATTERN_QUALITY_CHECK_SKIP")
    if not skip:
        skip_env = os.environ.get("SKIP", "").strip().lower()
        skip = "pattern-quality" in skip_env

    print("=" * 60)
    print("🔬 模式文档V2质量检查 (Pre-commit Hook)")
    print("=" * 60)
    if skip:
        print(f"\n⚠️  检测到跳过标记，已跳过模式质量检查。")
        print()
        return 0

    if str(scripts_dir) not in sys.path:
        sys.path.insert(0, str(scripts_dir))

    pattern_files = [
        f for f in staged_files
        if "docs/retrospective/patterns" in str(f).replace("\\", "/")
        and str(f).endswith(".md")
        and Path(f).name not in {"README.md", "CATEGORIES.md"}
    ]

    if not pattern_files:
        print("\n✅ 本次提交无模式文档变更，跳过检查。\n")
        return 0

    print(f"\n📋 待检查模式文件: {len(pattern_files)} 个")
    for f in pattern_files:
        print(f"   - {f}")

    try:
        from lib.check_pattern_quality.checker import check_pattern
    except ImportError as exc:
        print(f"\n⚠️  无法加载模式质量检查模块，跳过: {exc}")
        print()
        return 0

    errors = []
    for rel_path in pattern_files:
        abs_path = project_root / rel_path
        if not abs_path.exists():
            continue
        try:
            report = check_pattern(abs_path, project_root)
            file_errors = [
                r for r in report.results
                if not r.passed and r.severity == "error"
                and r.name.startswith("innovation.")
            ]
            if file_errors:
                errors.append((rel_path, file_errors))
        except Exception as e:
            print(f"   ⚠️  检查 {rel_path} 时出错: {e}")

    print()
    if errors:
        print(f"❌ 检测到 {len(errors)} 个模式文档V2质量不达标，提交已阻断！")
        print("-" * 60)
        for rel_path, errs in errors:
            print(f"\n  📄 {rel_path}:")
            for err in errs:
                print(f"     ✗ {err.message}")
        print("\n💡 修复方法:")
        print("  创新/跨领域类模式V2强制要求:")
        print("  1. 至少1个真实失败案例（章节标题含「失败案例」）")
        print("  2. 至少3类反目标用户/场景分析（章节标题含「不适用/反目标/边界场景」）")
        print("  3. 建议补充早期预警信号表（≥5个信号）")
        print("  4. 明确标注适用边界/前提条件")
        print("  参考: .agents/prompts/reverse-adaptation-innovation-v2-addendum.md")
        print("\n🔓 临时跳过方式（仅限紧急情况）:")
        print("  PATTERN_QUALITY_CHECK_SKIP=1 git commit")
        print("  git commit --no-verify  (跳过所有钩子，最不推荐)")
        print("=" * 60)
        return 1

    print("✅ 模式文档V2质量检查通过。\n")
    return 0


def _skip_future_annotations_check() -> tuple[bool, str]:
    """PEP 563 样板检查是否被环境变量跳过。"""
    if _env_truthy("FUTURE_ANNOTATIONS_SKIP"):
        return True, "FUTURE_ANNOTATIONS_SKIP=1"
    skip_env = os.environ.get("SKIP", "").strip().lower()
    if "future-annotations" in skip_env:
        return True, f"SKIP={os.environ.get('SKIP', '')}"
    return False, ""


def _run_future_annotations_check(project_root: Path, staged_files: list[Path]) -> int:
    """禁止 ``from __future__ import annotations``（PEP 563 样板）。

    与 pytest 守护门禁共用 ``lib.future_annotations`` 的扫描与豁免口径。
    """
    skip, skip_reason = _skip_future_annotations_check()
    print("=" * 60)
    print("🐍 PEP 563 样板检查 (Pre-commit Hook)")
    print("=" * 60)
    if skip:
        print(f"\n⚠️  检测到 {skip_reason}，已跳过 future annotations 检查。\n")
        return 0

    py_files = [f for f in staged_files if str(f).endswith(".py")]
    if not py_files:
        print("\n✅ 本次提交无 Python 文件变更，跳过检查。\n")
        return 0

    from lib.future_annotations import has_future_annotations, is_exempt

    offenders: list[Path] = []
    for rel in py_files:
        abs_path = project_root / rel
        if not abs_path.is_file() or is_exempt(abs_path, project_root):
            continue
        if has_future_annotations(abs_path):
            offenders.append(rel)

    if not offenders:
        print("\n✅ 暂存 Python 文件均未含该样板。\n")
        return 0

    print("\n❌ 检测到 PEP 563 future import，提交已阻断！")
    for rel in offenders:
        print(f"   - {rel}")
    print("\n💡 Python 3.14+ 已默认 PEP 649 惰性注解，直接删除该行；")
    print("   若注解引用后置定义的名字，改写为字符串注解。")
    print("🔓 临时跳过（仅限紧急情况）: FUTURE_ANNOTATIONS_SKIP=1 git commit\n")
    return 1


def _skip_ruff_check() -> tuple[bool, str]:
    """Ruff 检查是否被环境变量跳过。"""
    if _env_truthy("RUFF_CHECK_SKIP"):
        return True, "RUFF_CHECK_SKIP=1"
    skip_env = os.environ.get("SKIP", "").strip().lower()
    if "ruff-check" in skip_env:
        return True, f"SKIP={os.environ.get('SKIP', '')}"
    return False, ""


def _resolve_ruff_cmd() -> list[str] | None:
    """解析可用的 ruff 调用：RUFF_BIN > 当前解释器 -m ruff > PATH 上的 ruff。"""
    candidates: list[list[str]] = []
    ruff_bin = os.environ.get("RUFF_BIN", "").strip()
    if ruff_bin:
        candidates.append([ruff_bin])
    candidates.append([sys.executable, "-m", "ruff"])
    candidates.append(["ruff"])
    for cmd in candidates:
        try:
            result = subprocess.run(cmd + ["--version"], capture_output=True, text=True)
        except OSError:
            continue
        if result.returncode == 0:
            return cmd
    return None


def _ruff_config_roots(project_root: Path, py_files: list[Path]) -> dict[Path, list[Path]]:
    """按含 [tool.ruff] 的最近 pyproject.toml 对暂存 .py 文件分组。

    未启用 ruff 的项目（无配置）一律不纳入检查，避免对其他应用产生越界红线。
    """
    groups: dict[Path, list[Path]] = {}
    root_cache: dict[Path, Path | None] = {}
    for rel in py_files:
        cur = (project_root / rel).parent
        config_root: Path | None = None
        cur_key = cur
        while True:
            if cur_key in root_cache:
                cached = root_cache[cur_key]
                if cached is not None:
                    config_root = cached
                break
            pyproject = cur_key / "pyproject.toml"
            if pyproject.is_file():
                try:
                    if "[tool.ruff]" in pyproject.read_text(encoding="utf-8"):
                        config_root = cur_key
                except (OSError, UnicodeDecodeError):
                    pass
                root_cache[cur_key] = config_root
                break
            if cur_key == project_root or cur_key.parent == cur_key:
                root_cache[cur_key] = None
                break
            cur_key = cur_key.parent
        if config_root is not None:
            groups.setdefault(config_root, []).append(rel)
    return groups


def _run_ruff_check(project_root: Path, staged_files: list[Path]) -> int:
    """Ruff lint：仅检查启用了 [tool.ruff] 的应用中被暂存的 .py 文件。

    只读检查（不加 --fix），ruff 不可用时默认降级为提示，
    CI 可通过 RUFF_CHECK_REQUIRED=1 改为硬阻断。
    """
    skip, skip_reason = _skip_ruff_check()
    print("=" * 60)
    print("🐍 Ruff lint (Pre-commit Hook)")
    print("=" * 60)
    if skip:
        print(f"\n⚠️  检测到 {skip_reason}，已跳过 Ruff 检查。\n")
        return 0

    py_files = [f for f in staged_files if str(f).endswith(".py")]
    if not py_files:
        print("\n✅ 本次提交无 Python 文件变更，跳过检查。\n")
        return 0

    groups = _ruff_config_roots(project_root, py_files)
    if not groups:
        print("\n✅ 暂存的 Python 文件均不在启用 [tool.ruff] 的项目内，跳过检查。\n")
        return 0

    ruff_cmd = _resolve_ruff_cmd()
    if ruff_cmd is None:
        msg = (
            "\n⚠️  未找到 ruff（已尝试 RUFF_BIN、当前解释器 -m ruff、PATH）。\n"
            "   安装: pip install ruff（或安装对应应用的 dev 依赖）\n"
        )
        if _env_truthy("RUFF_CHECK_REQUIRED"):
            print(msg + "   RUFF_CHECK_REQUIRED=1：提交已阻断！\n")
            return 1
        print(msg + "   已降级跳过；设置 RUFF_CHECK_REQUIRED=1 可改为硬阻断。\n")
        return 0

    failed = False
    for config_root, files in groups.items():
        display_root = config_root.relative_to(project_root) if config_root != project_root else Path(".")
        print(f"\n📋 {display_root}: 检查 {len(files)} 个暂存 .py 文件")
        cmd = ruff_cmd + ["check"] + [str(project_root / f) for f in files]
        result = subprocess.run(cmd, cwd=str(config_root))
        if result.returncode != 0:
            failed = True

    if failed:
        print("\n" + "=" * 60)
        print("❌ Ruff 检测到红线问题，提交已阻断！")
        print("💡 按上方诊断修复；可自动修复的问题运行 ruff check --fix <文件>")
        print("🔓 临时跳过（仅限紧急情况）: RUFF_CHECK_SKIP=1 git commit")
        print("=" * 60)
        return 1

    print("\n✅ Ruff lint 通过。\n")
    return 0


def main() -> int:
    project_root = find_project_root()
    scripts_dir = project_root / ".agents" / "scripts"

    if str(scripts_dir) not in sys.path:
        sys.path.insert(0, str(scripts_dir))

    # 配置 stdout/stderr 编码安全模式，防止 GBK 等窄编码终端因 emoji
    # (📁🕒🔒) 输出而崩溃。必须在任何 print 之前调用。
    from lib.cli import setup_safe_output
    setup_safe_output()

    # 前置仓库状态检查（与暂存文件无关，每次提交均执行，快速失败）
    # 1. 关键配置文件放置校验（快：仅检查 7 个受管文件存在性）
    fp_result = _run_file_placement_check(project_root, scripts_dir)
    if fp_result != 0:
        return fp_result

    # 2. .temp/ 生命周期检查（只读，>30 天阻塞）
    tl_result = _run_temp_lifecycle_check(project_root, scripts_dir)
    if tl_result != 0:
        return tl_result

    staged_files = get_staged_files()

    if not staged_files:
        return 0

    result = _run_sensitive_check(project_root, scripts_dir, staged_files)
    if result != 0:
        return result

    pat_result = _run_pattern_quality_check(project_root, scripts_dir, staged_files)
    if pat_result != 0:
        return pat_result

    fa_result = _run_future_annotations_check(project_root, staged_files)
    if fa_result != 0:
        return fa_result

    ruff_result = _run_ruff_check(project_root, staged_files)
    if ruff_result != 0:
        return ruff_result

    try:
        from hooks.concurrent_check import run_concurrent_check
        return run_concurrent_check(project_root, staged_files)
    except ImportError as e:
        print("⚠️  并发安全检查模块未加载，跳过:", e)
        return 0


if __name__ == "__main__":
    sys.exit(main())

