#!/usr/bin/env python3
"""SessionStart hook: 会话开始时加载项目状态上下文"""
import json, subprocess, sys, os

project_dir = os.environ.get("CLAUDE_PROJECT_DIR", os.getcwd())
script = os.path.join(project_dir, "scripts", "audit", "prescan.py")

if not os.path.isfile(script):
    sys.exit(0)

try:
    r = subprocess.run(
        [sys.executable, script],
        capture_output=True, text=True, timeout=10, cwd=project_dir,
    )
    if r.returncode != 0:
        sys.exit(0)
    result = json.loads(r.stdout)
except Exception:
    sys.exit(0)

audit_required = result.get("audit_required", False)
total = result.get("total_files", 0)
tags = ", ".join(result.get("risk_tags", []))

if audit_required:
    ctx = f"[session-context] 当前工作区有 {total} 个未提交的变更文件，含高风险标签: {tags}。如果这些变更来自之前的会话且未审计，建议先执行 /audit。"
else:
    ctx = "[session-context] 当前工作区状态正常，无高风险未审计变更。"

print(json.dumps({
    "hookSpecificOutput": {
        "hookEventName": "SessionStart",
        "additionalContext": ctx
    }
}))
