#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""校验练习题 md 是否符合题库导入格式。
用法：python3 validate.py <file.md> [...]
检查项：
  1. 题号 1..N 连续、题型为 单选题/判断题
  2. 单选题恰好 4 个选项，A/B/C/D 齐全且顺序正确，选项之间无空行、无重复选项
  3. 答案格式合法（单选单个 A-D；判断 对/错）
  4. 每题 5 个字段齐全且有内容
  5. 统计：单选答案分布、判断对错分布、难度分布
"""
import re, sys

Q_RE = re.compile(r'^(\d+)\.【(单选题|判断题)】(.*)$')
OPT_RE = re.compile(r'^([A-E])\.(.*)$')
FIELD_RE = re.compile(r'^(答案|难易程度|答案解析|知识点|课程目标)：(.*)$')
REQUIRED = ['答案', '难易程度', '答案解析', '知识点', '课程目标']


def parse(path):
    with open(path, encoding='utf-8') as f:
        raw = f.read().splitlines()
    # 去掉文件头（第一个题号行之前的内容）
    start = next((i for i, l in enumerate(raw) if Q_RE.match(l)), None)
    if start is None:
        return None, ['文件里没有找到 "N.【单选题】" 形式的题目行']
    lines = raw[start:]
    blocks, cur = [], None
    for ln in lines:
        m = Q_RE.match(ln)
        if m:
            if cur:
                blocks.append(cur)
            cur = {'no': int(m.group(1)), 'type': m.group(2), 'stem': m.group(3).strip(),
                   'opts': [], 'fields': {}, 'blank_in_opts': False, 'raw': [ln]}
        elif cur is not None:
            cur['raw'].append(ln)
            if not ln.strip():
                if cur['opts'] and len(cur['opts']) < 4 and not cur['fields']:
                    cur['blank_in_opts'] = True
                continue
            mo = OPT_RE.match(ln)
            mf = FIELD_RE.match(ln)
            if mf:
                cur['fields'][mf.group(1)] = mf.group(2).strip()
            elif mo and cur['type'] == '单选题':
                cur['opts'].append((mo.group(1), mo.group(2).strip()))
            elif not cur['fields']:
                cur['stem'] += ln.strip()
    if cur:
        blocks.append(cur)
    return blocks, []


def check(path):
    blocks, errs = parse(path)
    print('=' * 78)
    print('文件：', path)
    if blocks is None:
        print('  ✗ ' + '；'.join(errs))
        return False
    ok = True
    if len(blocks) != 20:
        print(f'  ✗ 题目数 {len(blocks)}，应为 20'); ok = False
    seen_sc = seen_tf = 0
    ans_sc, ans_tf, diff = {}, {}, {}
    know = {}
    for i, b in enumerate(blocks, 1):
        tag = f'  第{b["no"]}题（{b["type"]}）'
        if b['no'] != i:
            print(tag + f' ✗ 题号应为 {i}'); ok = False
        if b['no'] <= 10 and b['type'] != '单选题':
            print(tag + ' ✗ 前 10 题应为单选题'); ok = False
        if b['no'] >= 11 and b['type'] != '判断题':
            print(tag + ' ✗ 后 10 题应为判断题'); ok = False
        if not b['stem'].strip():
            print(tag + ' ✗ 题干为空'); ok = False
        for f in REQUIRED:
            if f not in b['fields'] or not b['fields'][f]:
                print(tag + f' ✗ 缺少或有空字段：{f}'); ok = False
        a = b['fields'].get('答案', '')
        if b['type'] == '单选题':
            seen_sc += 1
            letters = [o[0] for o in b['opts']]
            if letters != ['A', 'B', 'C', 'D']:
                print(tag + f' ✗ 选项为 {letters}，应为 A/B/C/D 各一个'); ok = False
            texts = [o[1] for o in b['opts']]
            if len(set(texts)) != len(texts):
                print(tag + ' ✗ 选项内容有重复'); ok = False
            if b['blank_in_opts']:
                print(tag + ' ✗ 选项之间存在空行'); ok = False
            if a not in ('A', 'B', 'C', 'D'):
                print(tag + f' ✗ 单选答案非法：{a!r}'); ok = False
            ans_sc[a] = ans_sc.get(a, 0) + 1
        else:
            seen_tf += 1
            if a not in ('对', '错'):
                print(tag + f' ✗ 判断答案非法：{a!r}'); ok = False
            ans_tf[a] = ans_tf.get(a, 0) + 1
        d = b['fields'].get('难易程度', '')
        diff[d] = diff.get(d, 0) + 1
        if len(b['fields'].get('答案解析', '')) < 8:
            print(tag + ' ✗ 答案解析过短'); ok = False
        for k in [x.strip() for x in b['fields'].get('知识点', '').split('；') if x.strip()]:
            know[k] = know.get(k, 0) + 1
    print(f'  题目数：{len(blocks)}（单选 {seen_sc} / 判断 {seen_tf}）')
    print(f'  单选答案分布：{dict(sorted(ans_sc.items()))}')
    print(f'  判断对错分布：{dict(sorted(ans_tf.items()))}')
    print(f'  难度分布：{dict(sorted(diff.items()))}')
    rep = {k: v for k, v in know.items() if v >= 3}
    if rep:
        print(f'  ! 同一知识点出现 ≥3 次：{rep}')
    print('  → ' + ('通过' if ok else '存在错误'))
    return ok


if __name__ == '__main__':
    files = sys.argv[1:]
    allok = all(check(f) for f in files)
    sys.exit(0 if allok else 1)
