#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""按学校《试题出题模板》《试题答案样本》重排 12 套卷
输出：04-模板版成卷/学生卷-试题/  标准答案-评分标准/
体例：
  题卷：宋体16pt粗体居中校名 → 学年学期试题(卷) → 课程名称/课程代码 → 考试方式/考试时间 →
        学院/班级/学号/姓名 → 一、选择题 二、填空题 三、判断题 四、简答题 五、案例分析题
  答案卷：楷体_GB2312 18pt 三行标题 → 课程/代码 → 适用班级 → 出卷老师/考试方式/卷面总分
"""
import os, re, sys
from docx import Document
from docx.shared import Pt, Cm, Emu
from docx.enum.text import WD_ALIGN_PARAGRAPH
from docx.oxml.ns import qn
from docx.oxml import OxmlElement

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import build_papers as bp

BASE = bp.BASE
OUT = os.path.join(BASE, "04-模板版成卷")
DIR_Q = os.path.join(OUT, "学生卷-试题")
DIR_A = os.path.join(OUT, "标准答案-评分标准")
DIR_T = os.path.join(OUT, "机考导入TXT")

CLASSES = bp.CLASSES
TERM = "2026 /2027 学年第 1 学期"


def setfont(run, name="宋体", size=12, bold=None):
    run.font.name = name
    run.font.size = Pt(size)
    if bold is not None:
        run.font.bold = bold
    rPr = run._element.get_or_add_rPr()
    rf = rPr.find(qn("w:rFonts"))
    if rf is None:
        rf = OxmlElement("w:rFonts"); rPr.append(rf)
    rf.set(qn("w:ascii"), "Times New Roman")
    rf.set(qn("w:hAnsi"), "Times New Roman")
    rf.set(qn("w:eastAsia"), name)


def p(doc, text="", size=12, bold=False, align=None, font="宋体", first=0, left=0, line=1.5,
      before=0, after=0):
    par = doc.add_paragraph()
    pf = par.paragraph_format
    pf.line_spacing = line
    pf.space_before = Pt(before)
    pf.space_after = Pt(after)
    if first:
        pf.first_line_indent = Emu(int(first))
    if left:
        pf.left_indent = Emu(int(left))
    if align == "center":
        par.alignment = WD_ALIGN_PARAGRAPH.CENTER
    elif align == "justify":
        par.alignment = WD_ALIGN_PARAGRAPH.JUSTIFY
    if text:
        r = par.add_run(text)
        setfont(r, font, size, bold)
    return par


def add_field(par, instr):
    r = par.add_run()
    f1 = OxmlElement("w:fldChar"); f1.set(qn("w:fldCharType"), "begin")
    it = OxmlElement("w:instrText"); it.set(qn("xml:space"), "preserve"); it.text = instr
    f2 = OxmlElement("w:fldChar"); f2.set(qn("w:fldCharType"), "separate")
    t = OxmlElement("w:t"); t.text = "1"
    f3 = OxmlElement("w:fldChar"); f3.set(qn("w:fldCharType"), "end")
    r._r.append(f1); r._r.append(it); r._r.append(f2); r._r.append(t); r._r.append(f3)
    setfont(r, "宋体", 10.5)


def page_setup(doc, top=2.54, left=3.175):
    s = doc.sections[0]
    s.page_width, s.page_height = Cm(21.0), Cm(29.7)
    s.left_margin = s.right_margin = Cm(left)
    s.top_margin = s.bottom_margin = Cm(top)
    s.header_distance, s.footer_distance = Cm(1.5), Cm(1.75)
    st = doc.styles["Normal"]
    st.font.name = "宋体"; st.font.size = Pt(12)
    st.element.rPr.rFonts.set(qn("w:eastAsia"), "宋体")
    fp = s.footer.paragraphs[0]
    fp.alignment = WD_ALIGN_PARAGRAPH.CENTER
    r = fp.add_run("第 "); setfont(r, "宋体", 10.5)
    add_field(fp, "PAGE")
    r = fp.add_run(" 页 共 "); setfont(r, "宋体", 10.5)
    add_field(fp, "NUMPAGES")
    r = fp.add_run(" 页"); setfont(r, "宋体", 10.5)


def header_line(doc, cls, teacher=None):
    """页眉：左“使用班级”，右“出卷老师”，用无框表格保证两端对齐"""
    from docx.enum.table import WD_TABLE_ALIGNMENT
    sec = doc.sections[0]
    hp = sec.header.paragraphs[0]
    hp.paragraph_format.space_after = Pt(0)
    r = hp.add_run("")
    setfont(r, "宋体", 1)
    t = sec.header.add_table(rows=1, cols=2, width=Cm(14.6))
    t.alignment = WD_TABLE_ALIGNMENT.CENTER
    t.autofit = False
    tbl = t._tbl
    tblPr = tbl.tblPr
    borders = OxmlElement("w:tblBorders")
    for edge in ("top", "left", "bottom", "right", "insideH", "insideV"):
        el = OxmlElement(f"w:{edge}")
        el.set(qn("w:val"), "none"); el.set(qn("w:sz"), "0")
        borders.append(el)
    tblPr.append(borders)
    grid = tbl.tblGrid
    for i, gc in enumerate(grid.findall(qn("w:gridCol"))):
        gc.set(qn("w:w"), str(int(Cm(10.0 if i == 0 else 4.6).twips)))
    teacher = teacher or bp.TEACHER
    c0, c1 = t.cell(0, 0), t.cell(0, 1)
    c0.width = Cm(10.0); c1.width = Cm(4.6)
    p0 = c0.paragraphs[0]; p0.alignment = WD_ALIGN_PARAGRAPH.LEFT
    r0 = p0.add_run(f"使用班级：{cls}"); setfont(r0, "宋体", 10.5)
    p1 = c1.paragraphs[0]; p1.alignment = WD_ALIGN_PARAGRAPH.RIGHT
    r1 = p1.add_run(f"出卷老师：{teacher}"); setfont(r1, "宋体", 10.5)


def q_title(doc, pcode):
    p(doc, "广 东 金 融 学 院", size=16, bold=True, align="center", left=227965)
    p(doc, f"{TERM}考试试题（{pcode}）卷", size=16, bold=True, align="center", left=227965)
    p(doc, "", size=6)
    p(doc, "课程名称：软件项目管理                        课程代码：154431006", first=152400)
    p(doc, "考试方式：闭卷（机房计算机考试）        考试时间：120 分钟", first=152400)
    p(doc, "", size=6)
    p(doc, "学院____________  班级__________  学号___________  姓名__________", first=152400)


def a_title(doc, pcode, cls):
    p(doc, "广东金融学院", size=18, bold=True, align="center", font="楷体_GB2312", left=227965, line=1.35)
    p(doc, f"{TERM}考试试题", size=18, bold=True, align="center", font="楷体_GB2312", left=227965, line=1.35)
    p(doc, f"标准答案及评分标准（{pcode} 卷）", size=18, bold=True, align="center", font="楷体_GB2312", left=227965, line=1.35)
    p(doc, "", size=6)
    p(doc, "课程名称：软件项目管理        课程代码：154431006", left=455930, before=3)
    p(doc, f"适用班级：{cls}", left=455930, before=3)
    p(doc, f"出卷老师：{bp.TEACHER}    考试方式：闭卷（机考）    卷面总分：100 分", left=455930, before=3, after=6)


def sec_head(doc, text):
    p(doc, text, size=12, bold=True, first=151765, before=6, after=2)


def item_head(doc, no, text):
    p(doc, f"{no}、{text}", size=12, left=266700, line=1.5)


def option(doc, letter, text, inline=False):
    p(doc, f"{letter}．{text}", size=12, left=266700, line=1.5)


def strip_no(t):
    t = re.sub(r"^\s*[（(]\d+[)）]\s*", "", t or "")
    return re.sub(r"^\s*[（(][\d.]+\s*分[)）]\s*", "", t)


def build_question(pid, items, cls):
    doc = Document(); page_setup(doc)
    header_line(doc, cls)
    q_title(doc, pid[1])

    singles = [x for x in items if x["type"] == "single"]
    fills = [x for x in items if x["type"] == "fill"]
    tfs = [x for x in items if x["type"] == "tf"]
    shorts = [x for x in items if x["type"] == "short"]
    cases = [x for x in items if x["type"] == "case"]

    sec_head(doc, f"一、选择题（本题共 {len(singles)} 小题，每小题 1 分，共 {len(singles)} 分）")
    for i, it in enumerate(singles, 1):
        item_head(doc, i, it["stem"])
        for o in it["options"]:
            p(doc, o, size=12, left=266700, line=1.5)

    sec_head(doc, f"二、填空题（本题共 {len(fills)} 小题，每空 1 分，共 {len(fills)*2} 分）")
    for i, it in enumerate(fills, 1):
        item_head(doc, i, it["stem"])

    sec_head(doc, f"三、判断题（要求：正确打√，错误打×）（本题共 {len(tfs)} 小题，每小题 1 分，共 {len(tfs)} 分）")
    for i, it in enumerate(tfs, 1):
        item_head(doc, i, it["stem"])

    sec_head(doc, f"四、简答题（本题共 {len(shorts)} 小题，每小题 5 分，共 {len(shorts)*5} 分）")
    for i, it in enumerate(shorts, 1):
        item_head(doc, i, f"{it['stem']}（5 分）")

    sec_head(doc, f"五、案例分析题（本题共 {len(cases)} 小题，每小题 10 分，共 {len(cases)*10} 分）")
    for i, it in enumerate(cases, 1):
        p(doc, f"{i}、{it.get('title','案例')}（10 分）", size=12, bold=True, left=266700, before=6)
        p(doc, it.get("background", ""), size=12, first=304800, line=1.5)
        tb = it.get("table")
        if tb:
            if tb.get("caption"):
                p(doc, tb["caption"], size=10.5, align="center", before=3, after=3)
            from docx.enum.table import WD_TABLE_ALIGNMENT
            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
            for j, h in enumerate(header):
                c = t.cell(0, j); c.text = ""
                rr = c.paragraphs[0].add_run(h); setfont(rr, "宋体", 10.5, True)
                c.paragraphs[0].alignment = WD_ALIGN_PARAGRAPH.CENTER
            for r, row in enumerate(rows, 1):
                for j, v in enumerate(row):
                    c = t.cell(r, j); c.text = ""
                    rr = c.paragraphs[0].add_run(str(v)); setfont(rr, "宋体", 10.5)
                    c.paragraphs[0].alignment = WD_ALIGN_PARAGRAPH.CENTER
        for k, q in enumerate(it.get("questions", []), 1):
            p(doc, f"（{k}）{strip_no(q['q'])}（{q['points']} 分）", size=12, left=266700, line=1.5)
    p(doc, "", size=6)
    return doc


def build_answer(pid, items, cls, cites=None):
    doc = Document(); page_setup(doc, top=2.3, left=3.17)
    a_title(doc, pid[1], cls)
    singles = [x for x in items if x["type"] == "single"]
    fills = [x for x in items if x["type"] == "fill"]
    tfs = [x for x in items if x["type"] == "tf"]
    shorts = [x for x in items if x["type"] == "short"]
    cases = [x for x in items if x["type"] == "case"]

    sec_head(doc, f"一、选择题（本题共 {len(singles)} 小题，每小题 1 分，共 {len(singles)} 分）")
    for k in range(0, len(singles), 4):
        chunk = singles[k:k+4]
        txt = "        ".join(f"{k+i}、（{it['answer']}）" for i, it in enumerate(chunk, 1))
        p(doc, txt, size=12, left=266700, line=1.5)
        if cites:
            src = "；".join(f"{k+i}—" + "、".join(f"P{x}" for x in cites.get(it["slot"], []) or ["—"]) for i, it in enumerate(chunk, 1))
            p(doc, "教材出处：" + src, size=9, left=266700, line=1.3)

    sec_head(doc, f"二、填空题（本题共 {len(fills)} 小题，每空 1 分，共 {len(fills)*2} 分）")
    for i, it in enumerate(fills, 1):
        tag = ("（" + "、".join(f"P{x}" for x in cites[it["slot"]]) + "）") if (cites and cites.get(it["slot"])) else ""
        p(doc, f"{i}、{it['answers'][0]}；{it['answers'][1]}。{tag}", size=12, left=266700, line=1.5)

    sec_head(doc, f"三、判断题（要求：正确打√，错误打×）（本题共 {len(tfs)} 小题，每小题 1 分，共 {len(tfs)} 分）")
    for k in range(0, len(tfs), 5):
        chunk = tfs[k:k+5]
        txt = "        ".join(f"{k+i}、（{it['answer']}）" for i, it in enumerate(chunk, 1))
        p(doc, txt, size=12, left=266700, line=1.5)
        if cites:
            src = "；".join(f"{k+i}—" + "、".join(f"P{x}" for x in cites.get(it["slot"], []) or ["—"]) for i, it in enumerate(chunk, 1))
            p(doc, "教材出处：" + src, size=9, left=266700, line=1.3)

    sec_head(doc, f"四、简答题（本题共 {len(shorts)} 小题，每小题 5 分，共 {len(shorts)*5} 分）")
    for i, it in enumerate(shorts, 1):
        p(doc, f"{i}、（5 分）", size=12, left=266700)
        lines = []
        for seg in (it.get("answer") or "").split("\n"):
            lines.extend(split_points(seg))
        if lines:
            p(doc, "答：" + lines[0], size=12, left=266700, line=1.5)
            for ln in lines[1:]:
                p(doc, ln, size=12, left=304800, line=1.5)
        rubs = [f"（{k}）{strip_no(r)}" for k, r in enumerate(it.get("rubric") or [], 1)]
        if rubs:
            p(doc, "评分：" + "；".join(rubs), size=12, left=304800, line=1.5)
        if cites and cites.get(it["slot"]):
            p(doc, "教材出处：" + "、".join(f"P{x}" for x in cites[it["slot"]]), size=9, left=304800, line=1.3)

    sec_head(doc, f"五、案例分析题（本题共 {len(cases)} 小题，每小题 10 分，共 {len(cases)*10} 分）")
    for i, it in enumerate(cases, 1):
        p(doc, f"{i}、（10 分）", size=12, left=266700)
        lines = []
        for seg in (it.get("answer") or "").split("\n"):
            lines.extend(split_points(seg))
        if lines:
            p(doc, "解：" + lines[0], size=12, left=266700, line=1.5)
            for ln in lines[1:]:
                p(doc, ln, size=12, left=304800, line=1.5)
        rubs = [f"（{k}）{strip_no(r)}" for k, r in enumerate(it.get("rubric") or [], 1)]
        if rubs:
            p(doc, "评分：" + "；".join(rubs), size=12, left=304800, line=1.5)
        if cites and cites.get(it["slot"]):
            p(doc, "教材出处：" + "、".join(f"P{x}" for x in cites[it["slot"]]), size=9, left=304800, line=1.3)
    p(doc, "", size=6)
    return doc


def split_points(text):
    """在（1）（2）… 前断行，便于阅卷"""
    text = (text or "").strip()
    parts = re.split(r"(?=（[1-9]）)", text)
    return [x.strip() for x in parts if x.strip()]


def first_line(s):
    for ln in (s or "").split("\n"):
        if ln.strip():
            return ln.strip()
    return ""


def build_txt(pid, items, cls):
    """与卷面同序（选择→填空→判断→简答→案例）的机考导入文本"""
    order = {"single": 0, "fill": 1, "tf": 2, "short": 3, "case": 4}
    seq_items = sorted(items, key=lambda x: order[x["type"]])
    out = []
    for i, it in enumerate(seq_items, 1):
        t = it["type"]
        if t == "single":
            out.append(f"{i}.【单选题】{it['stem']}")
            out += it["options"]
            out.append(f"答案：{it['answer']}")
        elif t == "fill":
            out.append(f"{i}.【填空题】{it['stem']}")
            out.append("答案：" + "；".join(it["answers"]))
        elif t == "tf":
            out.append(f"{i}.【判断题】{it['stem']}")
            out.append("答案：" + ("对" if it["answer"] in ("√", "对") else "错"))
        elif t == "short":
            out.append(f"{i}.【简答题】{it['stem']}")
            out.append("答案：" + (it.get("answer") or "").replace("\n", " "))
        else:
            qs = "　".join(f"{q['q']}（{q['points']}分）" for q in it.get("questions", []))
            out.append(f"{i}.【案例分析题】{it.get('background','')}　{qs}")
            out.append("答案：" + (it.get("answer") or "").replace("\n", " "))
        out.append(f"难易程度：{it['difficulty']}")
        out.append(f"知识点：第{it['chapter']}章 {it.get('kp','')}")
        out.append(f"答案解析：{it.get('explain','') or '见参考答案'}")
        out.append("")
    return "\n".join(out)


def main():
    a, c = bp.load_all()
    P = bp.assemble(a, c)
    errs = bp.validate(a, c, P)
    if errs:
        print("[!] 校验失败", len(errs)); return
    os.makedirs(DIR_Q, exist_ok=True); os.makedirs(DIR_A, exist_ok=True)
    os.makedirs(DIR_T, exist_ok=True)
    for pid, items in P.items():
        cls = CLASSES[int(pid[0])]
        build_question(pid, items, cls).save(os.path.join(DIR_Q, f"{pid}-试题（{pid[1]}卷）.docx"))
        build_answer(pid, items, cls).save(os.path.join(DIR_A, f"{pid}-标准答案及评分标准（{pid[1]}卷）.docx"))
        with open(os.path.join(DIR_T, f"{pid}-机考导入（同卷序）.txt"), "w", encoding="utf-8") as f:
            f.write(build_txt(pid, items, cls))
    print(f"[OK] 模板版：{len(P)} 套试题 + {len(P)} 套答案 → {OUT}")


if __name__ == "__main__":
    main()
