#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import re, glob, json, os
BASE="/home/zyw/Downloads/dl-hub/22-软件项目管理教学包"
SRC=os.path.join(BASE,"练习题-推荐格式")

def parse(path, ch):
    txt=open(path,encoding="utf-8").read()
    blocks=[b.strip() for b in re.split(r"\n(?=\d+\.【)", txt) if b.strip()]
    items=[]
    for b in blocks:
        m=re.match(r"(\d+)\.【(.+?)】(.*)", b, re.S)
        if not m: continue
        no, typ, rest = m.groups()
        typ={"单选题":"single","多选题":"multi","判断题":"tf","填空题":"fill"}.get(typ, typ)
        lines=[x.strip() for x in rest.split("\n") if x.strip()]
        stem=[]; opts=[]; ans=""; diff=""; exp=""; kp=""
        for ln in lines:
            if ln.startswith("答案："): ans=ln[3:].strip()
            elif ln.startswith("难易程度："): diff=ln[5:].strip()
            elif ln.startswith("答案解析："): exp=ln[5:].strip()
            elif ln.startswith("知识点："): kp=ln[4:].strip()
            elif ln.startswith("课程目标："): pass
            elif re.match(r"^[A-D][\.．]", ln): opts.append(ln)
            else: stem.append(ln)
        items.append({"chapter":ch,"type":typ,"stem":"".join(stem).strip(),
                      "options":opts,"answer":ans,"difficulty":diff,"explain":exp,"kp":kp})
    return items

if __name__=="__main__":
    allitems=[]
    for f in sorted(glob.glob(os.path.join(SRC,"第*章*.txt"))):
        ch=int(re.search(r"第(\d+)章", f).group(1))
        allitems += parse(f, ch)
    json.dump(allitems, open("bank_1_7.json","w",encoding="utf-8"), ensure_ascii=False, indent=1)
    from collections import Counter
    print(len(allitems), Counter(x["chapter"] for x in allitems))
    print(Counter(x["type"] for x in allitems))
    print(Counter(x["difficulty"] for x in allitems))
