#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""生成 12 卷学生卷 / 教师卷（docx）、学习通导入 txt、双向细目表、命题审核表"""
import os, re, json
from docx import Document
from docx.shared import Pt, Cm, RGBColor
from docx.enum.text import WD_ALIGN_PARAGRAPH, WD_LINE_SPACING
from docx.enum.table import WD_TABLE_ALIGNMENT
from docx.enum.section import WD_SECTION
from docx.oxml.ns import qn
from docx.oxml import OxmlElement

BASE = "/home/zyw/Downloads/dl-hub/22-软件项目管理教学包/命题-2026秋"
OUT = os.path.join(BASE, "02-成卷")
TXT = os.path.join(BASE, "02-成卷", "机考导入TXT")

CLASSES = {1: "24计算机科学与技术-1班", 2: "24计算机科学与技术-2班",
           3: "24软件工程-1班", 4: "24软件工程-2班"}
TEACHER = "周宇文"
CHAPTER_NAME = {1: "软件项目管理概述", 2: "软件项目启动", 3: "软件项目采购管理", 4: "软件项目范围管理",
                5: "软件项目进度管理", 6: "软件项目成本管理", 7: "软件项目质量管理", 8: "软件项目资源管理",
                9: "软件项目干系人与沟通管理", 10: "软件项目风险管理"}
GOAL = {1: "课程目标1", 2: "课程目标1", 3: "课程目标1", 4: "课程目标2", 5: "课程目标2",
        6: "课程目标2", 7: "课程目标3", 8: "课程目标3", 9: "课程目标3", 10: "课程目标3"}
LEVEL = {"易": "识记／理解", "中": "应用／分析", "难": "综合／创新"}
TYPE_NAME = {"single": "单项选择题", "tf": "判断题", "fill": "填空题", "short": "简答题", "case": "案例分析题"}


def cnfont(run, name="宋体", size=12, bold=False, color=None):
    run.font.name = name
    run.font.size = Pt(size)
    run.font.bold = bold
    r = run._element.rPr.rFonts
    r.set(qn("w:eastAsia"), name)
    r.set(qn("w:ascii"), "Times New Roman" if name == "宋体" else name)
    r.set(qn("w:hAnsi"), "Times New Roman" if name == "宋体" else name)
    if color:
        run.font.color.rgb = RGBColor(*color)


def para(doc, text="", size=12, bold=False, align=None, font="宋体", indent=0, space_before=0,
         space_after=0, line=1.25, first_line=0, color=None):
    p = doc.add_paragraph()
    pf = p.paragraph_format
    pf.space_before = Pt(space_before)
    pf.space_after = Pt(space_after)
    pf.line_spacing = line
    if align == "center":
        p.alignment = WD_ALIGN_PARAGRAPH.CENTER
    elif align == "right":
        p.alignment = WD_ALIGN_PARAGRAPH.RIGHT
    elif align == "justify":
        p.alignment = WD_ALIGN_PARAGRAPH.JUSTIFY
    if indent:
        pf.left_indent = Cm(indent)
    if first_line:
        pf.first_line_indent = Pt(first_line * size)
    if text:
        r = p.add_run(text)
        cnfont(r, font, size, bold, color)
    return p


def add_field(paragraph, instr):
    r = paragraph.add_run()
    fld1 = OxmlElement("w:fldChar"); fld1.set(qn("w:fldCharType"), "begin")
    it = OxmlElement("w:instrText"); it.set(qn("xml:space"), "preserve"); it.text = instr
    fld2 = OxmlElement("w:fldChar"); fld2.set(qn("w:fldCharType"), "separate")
    t = OxmlElement("w:t"); t.text = "1"
    fld3 = OxmlElement("w:fldChar"); fld3.set(qn("w:fldCharType"), "end")
    r._r.append(fld1); r._r.append(it); r._r.append(fld2); r._r.append(t); r._r.append(fld3)
    cnfont(r, "宋体", 9)


def set_cell(cell, text, size=10.5, bold=False, align="center", font="宋体"):
    cell.text = ""
    p = cell.paragraphs[0]
    p.alignment = {"center": WD_ALIGN_PARAGRAPH.CENTER, "left": WD_ALIGN_PARAGRAPH.LEFT}[align]
    p.paragraph_format.space_before = Pt(1)
    p.paragraph_format.space_after = Pt(1)
    r = p.add_run(text)
    cnfont(r, font, size, bold)


def shade(cell, hexcolor="F2F2F2"):
    tcPr = cell._tc.get_or_add_tcPr()
    shd = OxmlElement("w:shd")
    shd.set(qn("w:val"), "clear"); shd.set(qn("w:color"), "auto"); shd.set(qn("w:fill"), hexcolor)
    tcPr.append(shd)


def set_col_widths(table, widths):
    table.autofit = False
    tbl = table._tbl
    grid = tbl.tblGrid
    for i, gc in enumerate(grid.findall(qn("w:gridCol"))):
        if i < len(widths):
            gc.set(qn("w:w"), str(int(widths[i].twips)))
    for row in table.rows:
        for i, cell in enumerate(row.cells):
            if i < len(widths):
                cell.width = widths[i]

def repeat_header(table):
    tr = table.rows[0]._tr
    trPr = tr.get_or_add_trPr()
    el = OxmlElement("w:tblHeader")
    el.set(qn("w:val"), "true")
    trPr.append(el)


def setup(doc, header_left, header_right):
    s = doc.sections[0]
    s.page_width, s.page_height = Cm(21.0), Cm(29.7)
    s.top_margin, s.bottom_margin = Cm(2.2), Cm(2.0)
    s.left_margin, s.right_margin = Cm(2.2), Cm(2.0)
    s.header_distance, s.footer_distance = Cm(1.2), Cm(1.2)
    st = doc.styles["Normal"]
    st.font.name = "宋体"; st.font.size = Pt(12)
    st.element.rPr.rFonts.set(qn("w:eastAsia"), "宋体")
    # header
    hp = s.header.paragraphs[0]
    hp.paragraph_format.space_after = Pt(2)
    r = hp.add_run(header_left)
    cnfont(r, "宋体", 9)
    hp.add_run("\t")
    r2 = hp.add_run(header_right)
    cnfont(r2, "宋体", 9)
    # bottom border on header paragraph
    pPr = hp._p.get_or_add_pPr()
    pbdr = OxmlElement("w:pBdr")
    bottom = OxmlElement("w:bottom")
    bottom.set(qn("w:val"), "single"); bottom.set(qn("w:sz"), "6")
    bottom.set(qn("w:space"), "1"); bottom.set(qn("w:color"), "808080")
    pbdr.append(bottom); pPr.append(pbdr)
    # footer
    fp = s.footer.paragraphs[0]
    fp.alignment = WD_ALIGN_PARAGRAPH.CENTER
    r = fp.add_run("第 "); cnfont(r, "宋体", 9)
    add_field(fp, "PAGE")
    r = fp.add_run(" 页　共 "); cnfont(r, "宋体", 9)
    add_field(fp, "NUMPAGES")
    r = fp.add_run(" 页"); cnfont(r, "宋体", 9)


def title_block(doc, pid, subtitle, exam_form="闭卷机考", is_teacher=False):
    cid = int(pid[0]); pcode = pid[1]
    para(doc, "", size=12, space_after=2)
    para(doc, "广东金融学院 2026—2027 学年第 1 学期期末考试", size=15, bold=True, align="center", font="黑体")
    para(doc, f"《软件项目管理》试卷（{pid} 卷）", size=18, bold=True, align="center", font="黑体", space_before=4)
    if is_teacher:
        para(doc, "参考答案与评分标准（教师用卷·请勿下发）", size=11, bold=True, align="center", color=(0xC0, 0x00, 0x00), space_after=4)
    else:
        para(doc, "", size=6)

    rows = [
        ("课程代码", "154431006", "课程性质", "专业必修课"),
        ("考试形式", exam_form, "考试时长", "120 分钟"),
        ("试卷满分", "100 分", "卷　　别", f"{pcode} 卷（{pid}）"),
        ("适用班级", CLASSES[cid], "命题方式", "统一命题·一班三卷"),
    ]
    t = doc.add_table(rows=4, cols=4)
    t.style = "Table Grid"
    t.alignment = WD_TABLE_ALIGNMENT.CENTER
    t.autofit = False
    widths = [Cm(2.2), Cm(7.0), Cm(2.2), Cm(5.2)]
    set_col_widths(t, widths)
    for i, row in enumerate(rows):
        for j, val in enumerate(row):
            c = t.cell(i, j)
            set_cell(c, val, size=9.5, bold=(j % 2 == 0))
            if j % 2 == 0:
                shade(c, "F2F2F2")
    para(doc, "", size=6, space_after=2)

    if not is_teacher:
        p = para(doc, "", size=9.5, space_before=2, space_after=1)
        r = p.add_run("学院：＿＿＿＿＿＿＿＿　　专业：＿＿＿＿＿＿＿＿　　班级：＿＿＿＿＿＿＿＿")
        cnfont(r, "宋体", 9.5)
        p = para(doc, "", size=9.5, space_before=0, space_after=1)
        r = p.add_run("学号：＿＿＿＿＿＿＿＿＿＿　　姓名：＿＿＿＿＿＿＿＿＿＿　　座位号：＿＿＿＿＿＿")
        cnfont(r, "宋体", 9.5)
        p = para(doc, "－－－－－－－－－－－－－－ 密　封　线（线内不得答题）－－－－－－－－－－－－－－", size=7.5, align="center", space_after=4)

    # score table
    heads = ["题　号", "一", "二", "三", "四", "五", "总　分"]
    vals = ["满　分", "20", "10", "20", "20", "30", "100"]
    t2 = doc.add_table(rows=2, cols=7)
    t2.style = "Table Grid"
    t2.alignment = WD_TABLE_ALIGNMENT.CENTER
    for j, h in enumerate(heads):
        set_cell(t2.cell(0, j), h, size=9, bold=True); shade(t2.cell(0, j), "F2F2F2")
    for j, v in enumerate(vals):
        set_cell(t2.cell(1, j), v, size=9, bold=(j == 0)); 
        if j == 0: shade(t2.cell(1, j), "F2F2F2")
    # 得分 row
    t2.add_row()
    for j, v in enumerate(["得　分", "", "", "", "", "", ""]):
        set_cell(t2.cell(2, j), v, size=9, bold=(j == 0))
        if j == 0: shade(t2.cell(2, j), "F2F2F2")
    para(doc, "", size=6, space_after=2)


def notes(doc):
    p = para(doc, "考生须知", size=10.5, bold=True, font="黑体", space_before=4, space_after=2)
    items = [
        "1. 本卷五大题、共 47 小题，满分 100 分，考试时间 120 分钟。考生须在机房考试系统中按题号顺序作答并提交。",
        "2. 单选题每题 1 分，四选一；判断题每题 1 分，正确选“√”、错误选“×”；填空题每空 1 分，须填写规范术语。",
        "3. 简答题按要点给分；案例分析题须写出公式、关键步骤与结论，只写结果不给全分。",
        "4. 计算结果保留两位小数；金额单位以题干标注为准。系统内置草稿纸功能，可在草稿区列式计算。",
        "5. 考试期间不得切换考试页面、不得使用通讯工具；凡雷同卷按学校考试纪律处理。",
    ]
    for it in items:
        para(doc, it, size=9.5, line=1.2)
    # 建议用时
    para(doc, "建议用时（合计 120 分钟）：单选 25 分钟｜判断 8 分钟｜填空 14 分钟｜简答 23 分钟｜案例 35 分钟｜检查 15 分钟",
         size=9, bold=True, space_before=2, space_after=2)


def item_paras(doc, item, no, show_answer=False):
    typ = item["type"]
    stem = item.get("stem", "")
    points = item.get("points")
    if typ in ("single", "tf"):
        p = para(doc, f"{no}. {stem}", size=11, line=1.25, space_before=3)
    elif typ == "fill":
        p = para(doc, f"{no}. 【第{item['chapter']}章】{stem}", size=11, line=1.25, space_before=3)
    if typ == "single":
        opts = item.get("options") or []
        for o in opts:
            para(doc, "　　" + o, size=11, line=1.15)
    if typ == "fill":
        pass
    if show_answer:
        if typ == "single":
            para(doc, f"　　【答案】{item['answer']}", size=10, bold=True, color=(0xC0, 0, 0))
            para(doc, f"　　【解析】{item.get('explain','')}", size=9.5, color=(0x33, 0x33, 0x33))
        elif typ == "tf":
            para(doc, f"　　【答案】{item['answer']}", size=10, bold=True, color=(0xC0, 0, 0))
            para(doc, f"　　【解析】{item.get('explain','')}", size=9.5, color=(0x33, 0x33, 0x33))
        elif typ == "fill":
            para(doc, f"　　【答案】（1）{item['answers'][0]}　（2）{item['answers'][1]}", size=10, bold=True, color=(0xC0, 0, 0))
            para(doc, f"　　【解析】{item.get('explain','')}", size=9.5, color=(0x33, 0x33, 0x33))


def case_block(doc, item, no, show_answer=False):
    tp = para(doc, f"{no}. {item.get('title','案例分析')}（本题 {item['points']} 分）", size=11, bold=True, space_before=6)
    tp.paragraph_format.keep_with_next = True
    if item.get("background"):
        para(doc, item["background"], size=10.5, line=1.3, first_line=2)
    tb = item.get("table")
    if tb:
        if tb.get("caption"):
            para(doc, tb["caption"], size=9, align="center", space_before=2, space_after=2)
        header, rows = tb.get("header", []), tb.get("rows", [])
        t = doc.add_table(rows=len(rows) + 1, cols=len(header))
        t.style = "Table Grid"
        t.alignment = WD_TABLE_ALIGNMENT.CENTER
        ncol = len(header)
        if ncol == 3:
            ws = [Cm(2.6), Cm(5.6), Cm(8.4)]
        elif ncol == 4:
            ws = [Cm(2.4), Cm(5.8), Cm(4.2), Cm(4.2)]
        else:
            ws = [Cm(16.6 / ncol)] * ncol
        set_col_widths(t, ws)
        for j, h in enumerate(header):
            set_cell(t.cell(0, j), h, size=9.5, bold=True); shade(t.cell(0, j), "F2F2F2")
        for i, row in enumerate(rows, 1):
            for j, v in enumerate(row):
                set_cell(t.cell(i, j), str(v), size=9.5)
    for i, q in enumerate(item.get("questions", []), 1):
        qt = re.sub(r"^\s*[（(]\d+[)）]\s*", "", q["q"])
        qt = re.sub(r"^\s*[（(][\d.]+\s*分[)）]\s*", "", qt)
        para(doc, f"（{i}）{qt}（{q['points']} 分）", size=10.5, line=1.25, first_line=0)
    if show_answer:
        para(doc, "【参考答案与评分标准】", size=10, bold=True, color=(0xC0, 0, 0), space_before=3)
        for line in (item.get("answer") or "").split("\n"):
            if not line.strip():
                continue
            para(doc, line, size=9.5, line=1.25, color=(0x22, 0x22, 0x22))


def build_student(doc, pid, items):
    cid = int(pid[0]); pcode = pid[1]
    setup(doc, "广东金融学院 2026—2027 学年第 1 学期期末考试",
          f"《软件项目管理》　试卷编号：154431006-{pid}")
    title_block(doc, pid, "")
    notes(doc)

    sections = [
        ("一、单项选择题（本大题共 20 小题，每小题 1 分，共 20 分；建议 25 分钟。每题只有一个正确选项）", "single", range(0, 20)),
        ("二、判断题（本大题共 10 小题，每小题 1 分，共 10 分；建议 8 分钟。正确选“√”，错误选“×”）", "tf", range(20, 30)),
        ("三、填空题（本大题共 10 小题，每小题 2 空，每空 1 分，共 20 分；建议 14 分钟）", "fill", range(30, 40)),
        ("四、简答题（本大题共 4 小题，每小题 5 分，共 20 分；建议 23 分钟。按要点作答）", "short", range(40, 44)),
        ("五、案例分析题（本大题共 3 小题，每小题 10 分，共 30 分；建议 35 分钟。须写出公式、关键步骤与结论）", "case", range(44, 47)),
    ]
    seq = 1
    for hdr, typ, rng in sections:
        hp = para(doc, hdr, size=11.5, bold=True, font="黑体", space_before=8, space_after=3)
        hp.paragraph_format.keep_with_next = True
        for idx in rng:
            it = items[idx]
            if typ == "case":
                case_block(doc, it, seq, show_answer=False)
            elif typ == "short":
                para(doc, f"{seq}. {it.get('stem','')}（5 分）", size=11, line=1.3, space_before=4, space_after=8)
            else:
                item_paras(doc, it, seq, show_answer=False)
            seq += 1
    para(doc, "", size=6)
    para(doc, "— 试卷结束 —", size=10, align="center")


def build_teacher(doc, pid, items):
    setup(doc, "广东金融学院 2026—2027 学年第 1 学期期末考试",
          f"《软件项目管理》　教师用卷：154431006-{pid}")
    title_block(doc, pid, "", is_teacher=True)
    para(doc, "本册含：一、答案速查；二、逐题答案与解析；三、主观题评分标准；四、双向细目表。", size=9.5, color=(0x55, 0x55, 0x55))

    # 答案速查
    para(doc, "一、客观题答案速查", size=12, bold=True, font="黑体", space_before=6)
    t = doc.add_table(rows=2, cols=11)
    t.style = "Table Grid"
    hdr = ["题号"] + [str(i) for i in range(1, 11)]
    set_cell(t.cell(0, 0), "单选1-10", size=8.5, bold=True); shade(t.cell(0, 0))
    for j in range(1, 11):
        set_cell(t.cell(0, j), str(j), size=8.5, bold=True); shade(t.cell(0, j))
    for j in range(1, 11):
        set_cell(t.cell(1, j), items[j-1]["answer"], size=9, bold=True)
    set_cell(t.cell(1, 0), "答案", size=8.5, bold=True); shade(t.cell(1, 0))
    t2 = doc.add_table(rows=2, cols=11)
    t2.style = "Table Grid"
    set_cell(t2.cell(0, 0), "单选11-20", size=8.5, bold=True); shade(t2.cell(0, 0))
    for j in range(1, 11):
        set_cell(t2.cell(0, j), str(10 + j), size=8.5, bold=True); shade(t2.cell(0, j))
    for j in range(1, 11):
        set_cell(t2.cell(1, j), items[10 + j - 1]["answer"], size=9, bold=True)
    set_cell(t2.cell(1, 0), "答案", size=8.5, bold=True); shade(t2.cell(1, 0))
    t3 = doc.add_table(rows=2, cols=11)
    t3.style = "Table Grid"
    set_cell(t3.cell(0, 0), "判断1-10", size=8.5, bold=True); shade(t3.cell(0, 0))
    for j in range(1, 11):
        set_cell(t3.cell(0, j), str(j), size=8.5, bold=True); shade(t3.cell(0, j))
    for j in range(1, 11):
        set_cell(t3.cell(1, j), items[20 + j - 1]["answer"], size=9, bold=True)
    set_cell(t3.cell(1, 0), "答案", size=8.5, bold=True); shade(t3.cell(1, 0))

    # 填空答案
    para(doc, "二、填空题答案（每空 1 分）", size=12, bold=True, font="黑体", space_before=8)
    t4 = doc.add_table(rows=11, cols=4)
    t4.style = "Table Grid"
    for j, h in enumerate(["题号", "（1）", "（2）", "所属章节"]):
        set_cell(t4.cell(0, j), h, size=9, bold=True); shade(t4.cell(0, j))
    for i, it in enumerate(items[30:40], 1):
        set_cell(t4.cell(i, 0), str(i), size=9)
        set_cell(t4.cell(i, 1), it["answers"][0], size=9)
        set_cell(t4.cell(i, 2), it["answers"][1], size=9)
        set_cell(t4.cell(i, 3), f"第{it['chapter']}章", size=9)

    # 逐题解析
    para(doc, "三、客观题逐题解析", size=12, bold=True, font="黑体", space_before=8)
    seq = 1
    for it in items[:20]:
        para(doc, f"{seq}. 【答案】{it['answer']}　【{it['difficulty']}·{it.get('kp','')}】", size=10, bold=True, space_before=2)
        para(doc, f"【解析】{it.get('explain','')}", size=9.5, color=(0x33, 0x33, 0x33))
        seq += 1
    for it in items[20:30]:
        para(doc, f"{seq}. 【答案】{it['answer']}　【{it['difficulty']}·{it.get('kp','')}】", size=10, bold=True, space_before=2)
        para(doc, f"【解析】{it.get('explain','')}", size=9.5, color=(0x33, 0x33, 0x33))
        seq += 1
    for i, it in enumerate(items[30:40], 1):
        para(doc, f"填空{i}. 【答案】（1）{it['answers'][0]}　（2）{it['answers'][1]}", size=10, bold=True, space_before=2)
        para(doc, f"【解析】{it.get('explain','')}", size=9.5, color=(0x33, 0x33, 0x33))

    # 主观题
    para(doc, "四、简答题参考答案与评分标准（每题 5 分）", size=12, bold=True, font="黑体", space_before=8)
    for i, it in enumerate(items[40:44], 1):
        para(doc, f"{i}. {it.get('stem','')}", size=10.5, bold=True, space_before=3)
        for line in (it.get("answer") or "").split("\n"):
            if line.strip():
                para(doc, line, size=9.5, line=1.25)
        para(doc, "【评分标准】" + "；".join(it.get("rubric") or []), size=9.5, color=(0xC0, 0, 0))

    para(doc, "五、案例分析题参考答案与评分标准（每题 10 分）", size=12, bold=True, font="黑体", space_before=8)
    for i, it in enumerate(items[44:47], 1):
        case_block(doc, it, i, show_answer=True)

    # 双向细目表
    doc.add_page_break()
    para(doc, "附表　双向细目表（命题审核用）", size=13, bold=True, font="黑体", align="center")
    para(doc, f"课程：软件项目管理（154431006）　卷别：{pid}　满分：100 分　时长：120 分钟", size=9, align="center")
    rows = []
    seq = 1
    for it in items:
        rows.append([seq, TYPE_NAME[it["type"]], f"第{it['chapter']}章", it.get("kp", ""), it["difficulty"],
                     it["points"], LEVEL[it["difficulty"]], GOAL[it["chapter"]]])
        seq += 1
    t5 = doc.add_table(rows=len(rows) + 2, cols=8)
    t5.style = "Table Grid"
    set_col_widths(t5, [Cm(1.2), Cm(2.2), Cm(1.3), Cm(5.3), Cm(1.2), Cm(1.2), Cm(2.4), Cm(2.0)])
    repeat_header(t5)
    heads = ["题号", "题型", "章节", "知识点", "难度", "分值", "能力层级", "课程目标"]
    for j, h in enumerate(heads):
        set_cell(t5.cell(0, j), h, size=8, bold=True); shade(t5.cell(0, j))
    for i, r in enumerate(rows, 1):
        for j, v in enumerate(r):
            set_cell(t5.cell(i, j), str(v), size=7.5)
    # 统计行
    from collections import Counter
    cd = Counter(); cl = Counter(); cc = Counter()
    for it in items:
        cd[it["difficulty"]] += it["points"]; cl[it["chapter"]] += it["points"]
    summary = f"难度：易{cd['易']}分／中{cd['中']}分／难{cd['难']}分（难题占{cd['难']}%）；章节：" + "、".join(
        f"{k}章{cl[k]}分" for k in sorted(cl))
    set_cell(t5.cell(len(rows) + 1, 0), summary, size=7.5, align="left")
    t5.cell(len(rows) + 1, 0).merge(t5.cell(len(rows) + 1, 7))


def build_txt(pid, items):
    lines = []
    seq = 1
    for it in items:
        t = it["type"]
        if t == "single":
            lines.append(f"{seq}.【单选题】{it['stem']}")
            for o in it["options"]:
                lines.append(o)
            lines.append(f"答案：{it['answer']}")
        elif t == "tf":
            ans = "对" if it["answer"] in ("√", "对") else "错"
            lines.append(f"{seq}.【判断题】{it['stem']}")
            lines.append(f"答案：{ans}")
        elif t == "fill":
            lines.append(f"{seq}.【填空题】{it['stem']}")
            lines.append("答案：" + "；".join(it["answers"]))
        elif t == "short":
            lines.append(f"{seq}.【简答题】{it['stem']}")
            lines.append("答案：" + (it.get("answer") or "").replace("\n", " "))
        else:
            qs = "　".join(f"{q['q']}（{q['points']}分）" for q in it.get("questions", []))
            lines.append(f"{seq}.【案例分析题】{it.get('background','')}　{qs}")
            lines.append("答案：" + (it.get("answer") or "").replace("\n", " "))
        lines.append(f"难易程度：{it['difficulty']}")
        lines.append(f"知识点：第{it['chapter']}章 {it.get('kp','')}")
        lines.append(f"答案解析：{it.get('explain','') or '见参考答案'}")
        lines.append("")
        seq += 1
    return "\n".join(lines)


def main():
    import build_papers as bp
    anchors, classes = bp.load_all()
    papers = bp.assemble(anchors, classes)
    errs = bp.validate(anchors, classes, papers)
    if errs:
        print(f"[!] 校验未通过，共 {len(errs)} 项，先修复再排版")
        for e in errs[:40]:
            print("  -", e)
        return
    os.makedirs(OUT, exist_ok=True)
    os.makedirs(TXT, exist_ok=True)
    for pid, items in papers.items():
        doc = Document(); build_student(doc, pid, items)
        doc.save(os.path.join(OUT, f"{pid}-学生卷.docx"))
        doc = Document(); build_teacher(doc, pid, items)
        doc.save(os.path.join(OUT, f"{pid}-教师卷（含答案）.docx"))
        with open(os.path.join(TXT, f"{pid}-机考导入.txt"), "w", encoding="utf-8") as f:
            f.write(build_txt(pid, items))
    print(f"[OK] 生成 {len(papers)} 卷，学生卷/教师卷/TXT 各 {len(papers)} 份 → {OUT}")


if __name__ == "__main__":
    main()
