File size: 4,370 Bytes
bc46b62
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
cli_v2.py — 一键执行 GDL→IR(v0.95)+ 校验 + 报告
改动要点:
1) policy 默认就是 merge(无需在命令行传参;也可用环境变量 GDL2IR_POLICY 覆盖)
2) 内置 schema 校验 & 自动发现 schema
   - 候选路径依次尝试:
     a) 命令行 --schema
     b) 脚本同目录的 poker_gdl_ir.schema.v0.95.zh.json
     c) 当前工作目录的 poker_gdl_ir.schema.v0.95.zh.json
     d) /mnt/data/poker_gdl_ir.schema.v0.95.zh.json
3) 兼容 validator_v2.validate_with_schema() 返回 2 元组或 3 元组
"""
import argparse, json, pathlib, sys, os

from gdl_parser_v2 import parse_gdl
from normalizer_v2 import normalize_ir
from mapper_v2 import map_to_v095
from validator_v2 import validate_with_schema
from gap_detector_v2 import make_report


def _auto_discover_schema(cli_arg: str = None) -> pathlib.Path:
    # 优先级:命令行 > 脚本同目录 > 当前目录 > /mnt/data
    candidates = []
    if cli_arg:
        candidates.append(cli_arg)

    here = pathlib.Path(__file__).resolve().parent
    candidates.append(str(here / "poker_gdl_ir.schema.v0.95.zh.json"))
    candidates.append("poker_gdl_ir.schema.v0.95.zh.json")
    candidates.append("/mnt/data/poker_gdl_ir.schema.v0.95.zh.json")

    for c in candidates:
        try:
            p = pathlib.Path(c)
            if p.exists():
                return p
        except Exception:
            pass

    raise FileNotFoundError(
        "未找到 Schema。请使用 --schema 指定,或将 poker_gdl_ir.schema.v0.95.zh.json 放在脚本同目录/当前目录。"
    )


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("gdl_file", help="源 GDL 文件(.txt/.gdl)")
    ap.add_argument("--schema", help="Schema 路径(可不填,将自动发现)")
    # policy 默认 merge;允许用环境变量 GDL2IR_POLICY 覆盖(可选)
    # ap.add_argument("--policy", choices=["minimal", "merge", "conservative"],
    #                 default=os.getenv("GDL2IR_POLICY", "merge"),
    #                 help="组合策略(默认 merge):"
    #                      "minimal=仅保留用到的;merge=保留通用并禁用无关;conservative=全保留")
    ap.add_argument("--out-ir", dest="out_ir", help="IR 输出 JSON 路径")
    ap.add_argument("--out-issues", dest="out_issues", help="校验问题 JSON 路径")
    ap.add_argument("--out-report", dest="out_report", help="自检报告 Markdown 路径")
    args = ap.parse_args()

    src_path = pathlib.Path(args.gdl_file)
    if not src_path.exists():
        print(f"[ERROR] 源文件不存在:{src_path}", file=sys.stderr)
        sys.exit(2)

    try:
        schema_path = _auto_discover_schema(args.schema)
    except FileNotFoundError as e:
        print(f"[ERROR] {e}", file=sys.stderr)
        sys.exit(2)

    # 读取 & 解析 & 规整
    gdl_txt = src_path.read_text(encoding="utf-8")
    gdl_ast = parse_gdl(gdl_txt)
    nz = normalize_ir(gdl_ast, gdl_txt)

    # 映射为 v0.95 IR(policy 默认 merge)
    ir = map_to_v095(nz, gdl_txt)

    # ✅ Schema 校验(兼容 2/3 元组返回)
    ret = validate_with_schema(ir, str(schema_path))
    if isinstance(ret, tuple) and len(ret) == 3:
        ok, issues, schema_msg = ret
    elif isinstance(ret, tuple) and len(ret) == 2:
        ok, issues = ret
        schema_msg = f"Schema: {'OK' if ok else 'FAIL'}; issues={len(issues)}"
    else:
        # 极端兜底:未知返回类型
        ok = bool(ret)
        issues = []
        schema_msg = f"Schema: {'OK' if ok else 'FAIL'}"

    # 输出
    out_ir = pathlib.Path(args.out_ir or str(src_path.with_suffix(".ir.v0.95.json")))
    out_issues = pathlib.Path(args.out_issues or str(src_path.with_suffix(".issues.json")))
    out_report = pathlib.Path(args.out_report or str(src_path.with_suffix(".selfcheck.md")))

    out_ir.write_text(json.dumps(ir, ensure_ascii=False, indent=2), encoding="utf-8")
    out_issues.write_text(json.dumps(issues, ensure_ascii=False, indent=2), encoding="utf-8")
    out_report.write_text(make_report(ir), encoding="utf-8")

    print(f"[OK] IR 写入:{out_ir}")
    print(f"[OK] Schema 校验问题写入:{out_issues}")
    print(f"[OK] 自检报告写入:{out_report}")
    print(f"[SUMMARY] {schema_msg}")

if __name__ == "__main__":
    main()