# -*- coding: utf-8 -*-
import json,sys
sys.path.insert(0,".")
import build_papers as bp
a,c=bp.load_all(); P=bp.assemble(a,c)
A=P["1A"]; B=json.load(open("b_items.json",encoding="utf-8"))
cites=json.load(open("citations.json",encoding="utf-8"))
CM={pid:{r["slot"]:r["pages"] for r in cites[pid]} for pid in ("1A","1B")}

def tbl(t):
    if not t: return ""
    out=["**"+t.get("caption","")+"**",""] if t.get("caption") else []
    head="| "+" | ".join(str(x) for x in t["header"])+" |"
    sep="|"+"|".join(["---"]*len(t["header"]))+"|"
    out.append(head); out.append(sep)
    for r in t["rows"]:
        out.append("| "+" | ".join(str(x) for x in r)+" |")
    return "\n".join(out)

def paper(pid,items,title):
    L=[f"# {title}",""]
    L.append("**课程**：软件项目管理　**课程代码**：154431006　**适用班级**：24 计算机科学与技术-1 班　"
             "**考试方式**：闭卷（机考）　**时间**：120 分钟　**总分**：100 分")
    L.append("")
    L.append("> 出卷人：周宇文　课程负责人：潘琪")
    L.append("")
    # 试题
    L.append("## 试题")
    seq={"single":"一、单项选择题（本大题共 20 小题，每小题 1 分，共 20 分）",
         "fill":"二、填空题（本大题共 10 小题，每空 1 分，共 20 分）",
         "tf":"三、判断题（正确打√，错误打×；本大题共 10 小题，每小题 1 分，共 10 分）",
         "short":"四、简答题（本大题共 4 小题，每小题 5 分，共 20 分）",
         "case":"五、案例分析题（本大题共 3 小题，每小题 10 分，共 30 分）"}
    for t in ("single","fill","tf","short","case"):
        its=[x for x in items if x["type"]==t]
        L.append(""); L.append("### "+seq[t]); L.append("")
        for i,it in enumerate(its,1):
            if t=="single":
                L.append(f"**{i}.** {it['stem']}")
                L.append("")
                for o in it["options"]: L.append(f"- {o}")
                L.append("")
            elif t=="fill":
                L.append(f"**{i}.** {it['stem']}（2 分）"); L.append("")
            elif t=="tf":
                L.append(f"**{i}.** {it['stem']}"); L.append("")
            elif t=="short":
                L.append(f"**{i}.** {it['stem']}（5 分）"); L.append("")
            else:
                L.append(f"**{i}.** {it.get('background','')}")
                L.append("")
                if it.get("table"):
                    L.append(tbl(it["table"])); L.append("")
                for q in it["questions"]:
                    L.append(f"- {q['q']}（{q.get('points',0)} 分）")
                L.append("")
    # 答案
    L.append("## 参考答案与评分标准")
    L.append("")
    for t in ("single","fill","tf","short","case"):
        its=[x for x in items if x["type"]==t]
        head={"single":"### 一、单项选择题","fill":"### 二、填空题","tf":"### 三、判断题",
              "short":"### 四、简答题","case":"### 五、案例分析题"}[t]
        L.append(head); L.append("")
        for i,it in enumerate(its,1):
            pg=CM[pid].get(it["slot"]) or []
            src=("（教材 "+"、".join("P"+str(x) for x in pg)+"）") if pg else ""
            if t=="single":
                L.append(f"**{i}、（{it['answer']}）**{src}")
            elif t=="fill":
                L.append(f"**{i}、{it['answers'][0]}；{it['answers'][1]}。**{src}")
            elif t=="tf":
                L.append(f"**{i}、（{it['answer']}）**{src}")
            else:
                L.append(f"**{i}、**")
                L.append("")
                L.append("答：")
                L.append("")
                L.append(it.get("answer",""))
                if it.get("rubric"):
                    L.append("")
                    L.append("评分："+"；".join(f"（{k}）{r}" for k,r in enumerate(it["rubric"],1))+"。")
                if src: L.append(""); L.append("教材出处："+src.strip("（）"))
            L.append("")
    return "\n".join(L)

md=[]
md.append("# 软件项目管理 期末试卷（A 卷、B 卷）")
md.append("")
md.append("> 广东金融学院　2026/2027 学年第 1 学期　课程代码 154431006")
md.append("> 出卷人：周宇文　课程负责人：潘琪")
md.append("> 本文件含 A、B 两卷试题与参考答案、评分标准；答案后标注教材页码。")
md.append("")
md.append("---")
md.append("")
md.append(paper("1A",A,"A 卷"))
md.append("")
md.append("---")
md.append("")
md.append(paper("1B",B,"B 卷"))
open("../11-AB重构/软件项目管理-A卷B卷（试题+答案）.md","w",encoding="utf-8").write("\n".join(md))
print("md chars", len("\n".join(md)))
