#!/usr/bin/env python3
"""validate_configs.py — 静态校验本目录的 Claude Code 配置示例（无需 key）。

校验内容：
1. JSON 语法（settings / mcp 示例）
2. 常见反模式扫描：配置文件里出现疑似真实 secret 的模式（sk-ant- 等）
3. 规则/技能/subagent 的 markdown frontmatter 必备字段

运行: python3 validate_configs.py  → 退出码 0 表示全部通过
"""

from __future__ import annotations

import json
import re
import sys
from pathlib import Path

HERE = Path(__file__).parent
FAIL: list[str] = []

SECRET_PATTERNS = [
    re.compile(r"sk-ant-[A-Za-z0-9_-]{20,}"),
    re.compile(r"xoxb-"),
    re.compile(r"AKIA[0-9A-Z]{16}"),
    re.compile(r"-----BEGIN [A-Z ]*PRIVATE KEY-----"),
]


def check(cond: bool, msg: str) -> None:
    print(("PASS " if cond else "FAIL ") + msg)
    if not cond:
        FAIL.append(msg)


def check_json(path: Path, required_keys: list[str]) -> None:
    try:
        data = json.loads(path.read_text(encoding="utf-8"))
    except Exception as e:  # noqa: BLE001
        check(False, f"{path.name}: JSON 解析失败: {e}")
        return
    check(True, f"{path.name}: JSON 语法有效")
    for key in required_keys:
        check(key in data, f"{path.name}: 含必需顶层键 '{key}'")
    if path.name == "settings-example.json":
        perms = data.get("permissions", {})
        check(bool(perms.get("deny")), "settings: permissions.deny 非空（默认拒绝思维）")
        allow = " ".join(perms.get("allow", []))
        check("Bash(*)" not in allow, "settings: allow 列表未使用 Bash(*) 全放行")
    if path.name == "mcp-example.json":
        raw = path.read_text(encoding="utf-8")
        check("${" in raw, "mcp: token 通过 ${ENV_VAR} 引用而非硬编码")
    # 所有文件扫 secret
    for p in HERE.rglob("*"):
        if p.suffix in {".json", ".md", ".py"}:
            text = p.read_text(encoding="utf-8")
            for pat in SECRET_PATTERNS:
                check(pat.search(text) is None, f"{p.name}: 未发现疑似真实密钥 ({pat.pattern[:12]}…)")


def check_frontmatter(path: Path, fields: list[str]) -> None:
    text = path.read_text(encoding="utf-8")
    m = re.match(r"^---\n(.*?)\n---\n", text, re.S)
    check(m is not None, f"{path.name}: 有 frontmatter")
    if not m:
        return
    for f in fields:
        check(re.search(rf"^{f}\s*:", m.group(1), re.M) is not None, f"{path.name}: frontmatter 含 '{f}'")


def main() -> int:
    print(f"== 校验 {HERE} ==")
    check_json(HERE / "settings-example.json", ["permissions", "hooks"])
    check_json(HERE / "mcp-example.json", ["mcpServers"])
    check_frontmatter(HERE / "rules-example.md", ["paths"])
    check_frontmatter(HERE / "subagent-example.md", ["name", "description", "tools"])
    check_frontmatter(HERE / "skill-example-SKILL.md", ["name", "description"])
    print(f"\n{'全部通过 ✔' if not FAIL else f'{len(FAIL)} 项失败 ✘'}")
    return 1 if FAIL else 0


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