#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""生成命题审核表（docx）与双向细目表（xlsx）"""
import os, sys
from docx import Document
from docx.shared import Pt, Cm
from docx.enum.text import WD_ALIGN_PARAGRAPH
from docx.enum.table import WD_TABLE_ALIGNMENT
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
import make_docx as md

BASE = bp.BASE
AUD = os.path.join(BASE, "03-审核材料")
TYPE_NAME = md.TYPE_NAME


def audit_doc(papers, times):
    doc = Document()
    s = doc.sections[0]
    s.page_width, s.page_height = Cm(21.0), Cm(29.7)
    s.left_margin = s.right_margin = Cm(2.0)
    s.top_margin = s.bottom_margin = Cm(2.0)
    st = doc.styles["Normal"]; st.font.name = "宋体"; st.font.size = Pt(10.5)
    st.element.rPr.rFonts.set(qn("w:eastAsia"), "宋体")

    for cid, cname in bp.CLASSES.items():
        if cid > 1:
            doc.add_page_break()
        md.para(doc, "广东金融学院课程考试命题审核表", size=16, bold=True, font="黑体", align="center", space_before=4)
        md.para(doc, "（2026—2027 学年第 1 学期）", size=10.5, align="center", space_after=6)

        rows = [
            ("开课单位", "计算机学院", "课程名称", "软件项目管理"),
            ("课程代码", "154431006", "课程性质", "专业必修课"),
            ("适用专业", "计算机科学与技术、软件工程、数据科学与大数据技术", "适用班级", cname),
            ("考试形式", "闭卷（机房计算机考试）", "考试时长／满分", "120 分钟／100 分"),
            ("命题方式", "统一命题（同一班级 A/B/C 三卷）", "命题人", "＿＿＿＿＿"),
            ("审核人", "＿＿＿＿＿", "审核日期", "2026 年 11 月 ＿＿ 日"),
        ]
        t = doc.add_table(rows=len(rows), cols=4); t.style = "Table Grid"; t.alignment = WD_TABLE_ALIGNMENT.CENTER
        md.set_col_widths(t, [Cm(2.8), Cm(6.2), Cm(2.8), Cm(6.2)])
        for i, r in enumerate(rows):
            for j, v in enumerate(r):
                md.set_cell(t.cell(i, j), v, size=9.5, bold=(j % 2 == 0),
                            align="center" if j % 2 == 0 else "left")
                if j % 2 == 0:
                    md.shade(t.cell(i, j), "F2F2F2")

        md.para(doc, "", size=6)
        md.para(doc, "一、命题依据与试卷结构", size=11, bold=True, font="黑体", space_before=4)
        md.para(doc, "依据《软件项目管理》课程教学大纲（2026-08-20）、课程考核方案及学校课程考核与学分绩点管理规定，"
                     "按“两性一度”要求命题。全卷 5 大题、47 小题，卷面 100 分。", size=9.5, line=1.3)

        # 结构统计
        items = papers[f"{cid}A"]
        stat = {}
        for it in items:
            stat.setdefault(it["type"], [0, 0])
            stat[it["type"]][0] += 1
            stat[it["type"]][1] += it["points"]
        md.para(doc, "题型结构：", size=9.5, bold=True, space_before=4)
        t2 = doc.add_table(rows=2, cols=6); t2.style = "Table Grid"
        heads = ["题型", "单选", "判断", "填空", "简答", "案例分析"]
        for j, h in enumerate(heads):
            md.set_cell(t2.cell(0, j), h, size=9, bold=True); md.shade(t2.cell(0, j), "F2F2F2")
        vals = ["题量／分值"] + [f"{stat.get(k,[0,0])[0]} 题／{stat.get(k,[0,0])[1]} 分"
                                  for k in ["single", "tf", "fill", "short", "case"]]
        for j, v in enumerate(vals):
            md.set_cell(t2.cell(1, j), v, size=9)

        # 章节分布
        ch = {}
        for it in items:
            ch[it["chapter"]] = ch.get(it["chapter"], 0) + it["points"]
        md.para(doc, "章节分值分布（覆盖全部 10 章）：", size=9.5, bold=True, space_before=6)
        t3 = doc.add_table(rows=2, cols=11); t3.style = "Table Grid"
        md.set_cell(t3.cell(0, 0), "章节", size=8.5, bold=True); md.shade(t3.cell(0, 0), "F2F2F2")
        md.set_cell(t3.cell(1, 0), "分值", size=8.5, bold=True); md.shade(t3.cell(1, 0), "F2F2F2")
        for k in range(1, 11):
            md.set_cell(t3.cell(0, k), f"{k}", size=8.5, bold=True); md.shade(t3.cell(0, k), "F2F2F2")
            md.set_cell(t3.cell(1, k), str(ch.get(k, 0)), size=8.5)
        md.para(doc, "说明：第 8 章仅考 8.1 资源管理基本概念，第 9 章仅考 9.1 干系人管理概述，"
                     "第 11 章不单独命题，故三章分值相应压缩。", size=8.5, color=(0x55, 0x55, 0x55))

        # 难度与时间
        from collections import Counter
        dif = Counter()
        for it in items:
            dif[it["difficulty"]] += it["points"]
        tm = times[f"{cid}A"]
        md.para(doc, f"难度结构：易 {dif['易']} 分／中 {dif['中']} 分／难 {dif['难']} 分（难题占 {dif['难']}%，"
                     f"符合 15%—25% 要求）。", size=9.5, space_before=6)
        md.para(doc, f"作答负荷：按单题用时模型测算，期望完成 {tm['total']:.1f} 分钟，P80 完成 {tm['p80']:.1f} 分钟"
                     f"（≤120 分钟），约 80% 学生可在规定时间内完成；考试过半（60 分钟）时案例 30 分尚未作答，"
                     f"不构成“半数以上提前交卷”。", size=9.5, line=1.3)

        # 卷别与重合度
        md.para(doc, "二、卷别设置与重合度控制", size=11, bold=True, font="黑体", space_before=8)
        md.para(doc, "本课程 4 个班在实验室分场次进行计算机考试，同一班级相邻场次存在题目外泄风险，故每班命 A/B/C 三卷；"
                     "同班三卷共用 5 道锚题与 16 道班内共享题，重合度 44.7%（≤60%）；四个班之间仅共用 5 道锚题，"
                     "重合度 10.6%（≤20%）。详见《重合度核算报告》。", size=9.5, line=1.3)

        t4 = doc.add_table(rows=5, cols=5); t4.style = "Table Grid"
        md.set_col_widths(t4, [Cm(2.6), Cm(4.0), Cm(3.4), Cm(3.4), Cm(3.4)])
        for j, h in enumerate(["卷别", "试卷编号", "使用场次", "命题人", "备注"]):
            md.set_cell(t4.cell(0, j), h, size=9, bold=True); md.shade(t4.cell(0, j), "F2F2F2")
        for i, pc in enumerate("ABC", 1):
            for j, v in enumerate([f"{pc} 卷", f"154431006-{cid}{pc}", f"第 {i} 场", "＿＿＿", "机考"]):
                md.set_cell(t4.cell(i, j), v, size=9)
        md.set_cell(t4.cell(4, 0), "说明", size=9, bold=True); md.shade(t4.cell(4, 0), "F2F2F2")
        c = t4.cell(4, 1); c.merge(t4.cell(4, 4))
        md.set_cell(c, "三卷同质同难、题型分值一致；仅题目情境与数据不同，防止相邻场次泄题。", size=8.5, align="left")

        # 审核意见（另起一页，留足签字空间）
        doc.add_page_break()
        md.para(doc, "三、审核意见", size=12, bold=True, font="黑体", space_before=2)
        t5 = doc.add_table(rows=4, cols=2); t5.style = "Table Grid"
        md.set_col_widths(t5, [Cm(3.2), Cm(14.6)])
        labels = ["教研室\n主任意见", "教学单位\n审核意见", "教务处\n备案", "备注"]
        for i, lab in enumerate(labels):
            md.set_cell(t5.cell(i, 0), lab, size=9.5, bold=True); md.shade(t5.cell(i, 0), "F2F2F2")
            md.set_cell(t5.cell(i, 1), "", size=9.5, align="left")
            t5.rows[i].height = Cm(4.2 if i < 2 else 2.2)
        md.para(doc, "注：本表一式两份，开课单位留存一份、报教务处备案一份；按学校规定，非闭卷考核方式须经开课单位审核批准并报教务处备案。"
                     "同一课程代码、名称的试卷如需按专业拆卷，已在上表“适用班级”栏写明专业名称。",
                size=8.5, color=(0x55, 0x55, 0x55), space_before=6)

    out = os.path.join(AUD, "命题审核表（1—4班）.docx")
    doc.save(out)
    return out


def xlsx_spec(papers, mat=None, times=None):
    from openpyxl import Workbook
    from openpyxl.styles import Font, Alignment, PatternFill, Border, Side
    wb = Workbook()
    ws = wb.active; ws.title = "双向细目表"
    headers = ["卷号", "题号", "题型", "章节", "知识点", "难度", "分值", "能力层级", "课程目标", "题干摘要"]
    ws.append(headers)
    thin = Side(style="thin", color="BBBBBB")
    border = Border(left=thin, right=thin, top=thin, bottom=thin)
    for c in ws[1]:
        c.font = Font(bold=True, name="微软雅黑", size=10)
        c.fill = PatternFill("solid", fgColor="E8EEF7")
        c.border = border
    for pid in sorted(papers):
        for i, it in enumerate(papers[pid], 1):
            stem = (it.get("stem") or it.get("title") or "").replace("\n", " ")[:60]
            ws.append([pid, i, TYPE_NAME[it["type"]], it["chapter"], it.get("kp", ""), it["difficulty"],
                       it["points"], md.LEVEL[it["difficulty"]], md.GOAL[it["chapter"]], stem])
    widths = [8, 6, 12, 6, 34, 6, 6, 12, 12, 60]
    for i, w in enumerate(widths, 1):
        ws.column_dimensions[chr(64 + i)].width = w
    for row in ws.iter_rows(min_row=2):
        for c in row:
            c.border = border
            c.alignment = Alignment(vertical="center", wrap_text=(c.column == 5 or c.column == 10))

    ws2 = wb.create_sheet("统计")
    ws2.append(["卷号", "总分", "易分", "中分", "难分", "难题占比", "期望用时(min)", "P80(min)", "班内重合", "班间重合"])
    for c in ws2[1]:
        c.font = Font(bold=True)
    for pid in sorted(papers):
        items = papers[pid]
        d = {"易": 0, "中": 0, "难": 0}
        for it in items:
            d[it["difficulty"]] += it["points"]
        t = (times or {}).get(pid, {})
        win = cross = ""
        if mat:
            c = pid[0]
            ws_ = [v[0] for k, v in mat.items()
                   if k[0][0] == c and k[1][0] == c and pid in k]
            xs = [v[0] for k, v in mat.items()
                  if k[0][0] != k[1][0] and pid in k]
            if ws_:
                win = f"{max(ws_)/47*100:.1f}%"
            if xs:
                cross = f"{max(xs)/47*100:.1f}%"
        ws2.append([pid, sum(d.values()), d["易"], d["中"], d["难"], f"{d['难']}%",
                    round(t.get("total", 0), 1), round(t.get("p80", 0), 1), win, cross])
    for col, w in zip("ABCDEFGHIJ", [8, 8, 6, 6, 6, 10, 14, 10, 10, 10]):
        ws2.column_dimensions[col].width = w
    out = os.path.join(AUD, "双向细目表（12卷）.xlsx")
    wb.save(out)
    return out


if __name__ == "__main__":
    a, c = bp.load_all()
    P = bp.assemble(a, c)
    errs = bp.validate(a, c, P)
    if errs:
        print("校验未通过", len(errs)); sys.exit(1)
    times = bp.time_budget(P)
    mat = bp.overlap_matrix(P)
    os.makedirs(AUD, exist_ok=True)
    print(audit_doc(P, times))
    print(xlsx_spec(P, mat, times))
