# -*- coding: utf-8 -*-
import json, os
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
from PIL import Image
from collections import Counter

BASE="/home/zyw/Downloads/dl-hub/22-软件项目管理教学包/命题-2026秋/10-知识图谱"
d=json.load(open("/home/zyw/Downloads/dl-hub/22-软件项目管理教学包/命题-2026秋/工作区/kg2.json",encoding="utf-8"))
nodes=d["nodes"]; pages=[p for n in nodes for p in n["pages"]]
def F(run,name="宋体",size=10.5,bold=False):
    run.font.name=name; run.font.size=Pt(size); 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:eastAsia"),name); rf.set(qn("w:ascii"),"Times New Roman"); rf.set(qn("w:hAnsi"),"Times New Roman")
def P(doc,text="",size=10.5,bold=False,align=None,font="宋体",before=0,after=0,first=0,line=1.4):
    p=doc.add_paragraph(); pf=p.paragraph_format
    pf.space_before=Pt(before); pf.space_after=Pt(after); pf.line_spacing=line
    if first: pf.first_line_indent=Pt(first*size)
    if align=="center": p.alignment=WD_ALIGN_PARAGRAPH.CENTER
    if text: r=p.add_run(text); F(r,font,size,bold)
    return p
def shade(c,h):
    tcPr=c._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"),h); tcPr.append(shd)
def cell(c,t,size=9,bold=False):
    c.text=""; p=c.paragraphs[0]; p.alignment=WD_ALIGN_PARAGRAPH.CENTER
    p.paragraph_format.space_before=Pt(1); p.paragraph_format.space_after=Pt(1)
    r=p.add_run(t); F(r,"宋体",size,bold)

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

P(doc,"《软件项目管理》课程知识图谱",17,True,"center",font="黑体")
P(doc,"——依据使用教材逐页构建（宋莹莹等《软件项目管理与实践》第3版，第1—14、15—248页）",10,False,"center")
P(doc,"",6)
P(doc,"一、构建方法",11.5,True,font="黑体",before=4,after=3)
for t_ in [
 "1. 底本：使用教材第 1—10 章的逐页 OCR 文本（含原书页码）。第 1 章 14 页、第 2 章 18 页、第 3—10 章按页转录，页码取自教材页脚。",
 "2. 层级：按“章—节—小节—概念/方法/工具”四级抽取。节、小节以教材正文标题为准；概念只收录教材以加粗编号条目或四级标题列出的名称，不收录命题人自行归纳的表述。",
 "3. 出处：每个节点记录教材页码，多页出现合并记录。节点表最后一列可直接回查原书。",
 "4. 排序：同章内按节号、小节号排序；概念按教材出现顺序排列。",
]:
    P(doc,t_,10.5,first=2,after=2)
P(doc,"二、规模",11.5,True,font="黑体",before=6,after=3)
c=Counter(n["level"] for n in nodes)
P(doc,f"全图 {len(nodes)} 个节点：章 {c['章']}、节 {c['节']}、小节 {c['小节']}、概念/方法/工具 {c['概念']}；出处覆盖教材第 {min(pages)}—{max(pages)} 页，共 {len(set(pages))} 个页面。",10.5,first=2,after=3)
rows=[["章节","章","节","小节","概念","合计"]]
for ch in range(1,11):
    cc=Counter(n["level"] for n in nodes if n["chapter"]==ch)
    rows.append([f"第{ch}章",cc["章"],cc["节"],cc["小节"],cc["概念"],sum(cc.values())])
rows.append(["合计",c["章"],c["节"],c["小节"],c["概念"],len(nodes)])
t=doc.add_table(rows=len(rows),cols=6); t.style="Table Grid"; t.alignment=WD_TABLE_ALIGNMENT.CENTER
for i,row in enumerate(rows):
    for j,v in enumerate(row):
        cell(t.cell(i,j),str(v),9,i in (0,len(rows)-1))
        if i in (0,len(rows)-1): shade(t.cell(i,j),"DCE6F5")
for row in t.rows:
    for j,w in enumerate([3.2,1.6,1.8,1.8,1.8,1.8]): row.cells[j].width=Cm(w)
P(doc,"",6)
P(doc,"三、总览（章—节）",11.5,True,font="黑体",before=4,after=3)
def add_img(path,maxw=17.0,maxh=22.0):
    im=Image.open(path); w,h=im.size
    doc.add_picture(path,width=Cm(min(maxw,maxh*w/h)))
    doc.paragraphs[-1].alignment=WD_ALIGN_PARAGRAPH.CENTER
add_img(os.path.join(BASE,"00-总览-章与节.png"),17.0,23.0)
P(doc,"四、分章图谱",11.5,True,font="黑体",before=8,after=3)
P(doc,"以下按章展开，展示“章—节—小节—概念”完整层级；图下列出该章概念清单及页码。",10.5,first=2,after=4)
for ch in range(1,11):
    doc.add_page_break()
    nm=[n["name"] for n in nodes if n["chapter"]==ch and n["level"]=="章"][0]
    P(doc,f"（{ch}）{nm}",12,True,font="黑体",before=0,after=4)
    fp=os.path.join(BASE,f"分章-{ch:02d}-{nm}.png")
    if os.path.exists(fp): add_img(fp,17.0,19.0)
    cs=[n for n in nodes if n["chapter"]==ch and n["level"]=="概念"]
    if cs:
        P(doc,"概念清单（名称｜教材页码）：",9.5,True,before=4,after=2)
        P(doc,"；".join(f"{n['name']}（{'、'.join('P'+str(p) for p in n['pages'])}）" for n in cs),9,after=2,line=1.3)
doc.add_page_break()
P(doc,"五、口径说明与局限",11.5,True,font="黑体",before=0,after=3)
for t_ in [
 "1. 第 1 章已补入教材原文（第 1—14 页），含 1.1、1.2、1.3 三节与 1.2.1—1.3.3 六个小节，概念节点按教材加粗条目与四级标题收录。",
 "2. 个别节因教材分页与标题合并（如 5.1 与 5.2 同页），图中以邻近节合并呈现；节点表保留原编号。",
 "3. 概念只取教材显性标题条目，“敏捷方法的应用”“实验”等节的工具名可能少于正文提及；如需扩展，可按同一方法继续补充正文术语。",
 "4. 本图是可复核的教材结构图，不是官方知识点清单；若教研室另有知识点表，可按同一层级映射。",
]:
    P(doc,t_,10.5,first=2,after=2)
P(doc,"六、用途",11.5,True,font="黑体",before=6,after=3)
P(doc,"① 命题覆盖核算；② 组卷选题与查重；③ 按章生成带页码的知识点清单，用于复习资料。",10.5,first=2,after=8)
P(doc,"周宇文",10.5,after=2)
P(doc,"2026 年 11 月    日",10.5,after=2)
doc.save(os.path.join(BASE,"课程知识图谱说明.docx"))
print("saved",len(nodes),dict(c))
