# -*- coding: utf-8 -*-
import json, os
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
from matplotlib import font_manager as fm
from collections import defaultdict

FONT="/usr/share/fonts/opentype/source-han-cjk/SourceHanSansSC-Regular.otf"
fp=fm.FontProperties(fname=FONT)
OUT="/home/zyw/Downloads/dl-hub/22-软件项目管理教学包/命题-2026秋/10-知识图谱"
d=json.load(open("kg2.json",encoding="utf-8"))
nodes={n["id"]:n for n in d["nodes"]}
children=defaultdict(list)
for a,b in d["edges"]:
    children[a].append(b)

import re as _re
def _key(cid):
    nm=nodes[cid]["name"]
    m=_re.match(r"(\d+(?:\.\d+)*)",nm)
    return [int(x) for x in m.group(1).split(".")] if m else [99]

def layout(root, maxdepth=9):
    pos={}; leaf=[0]
    def rec(nid,depth):
        ch=sorted([c for c in children.get(nid,[]) if c in nodes and depth<maxdepth], key=_key)
        if not ch:
            y=leaf[0]; leaf[0]+=1
            pos[nid]=(depth,y); return y
        ys=[rec(c,depth+1) for c in ch]
        y=sum(ys)/len(ys)
        pos[nid]=(depth,y); return y
    rec(root,0)
    return pos

def draw(root,fname,title,figw=15,fs=8,label_w=60,maxdepth=9):
    pos=layout(root,maxdepth)
    ys=[p[1] for p in pos.values()]; nleaf=max(ys) if ys else 1
    figh=max(6,min(30,0.34*nleaf+2))
    fig,ax=plt.subplots(figsize=(figw,figh))
    for a,b in d["edges"]:
        if a in pos and b in pos:
            x1,y1=pos[a]; x2,y2=pos[b]
            ax.plot([x1,x2],[y1,y2],color="#C3CEDF",lw=0.7,zorder=1)
    for nid,(x,y) in pos.items():
        n=nodes[nid]; lv=n["level"]
        color={"章":"#1F3B63","节":"#2E5C8A","小节":"#5B8FC9","概念":"#A9C0DA"}[lv]
        s={"章":180,"节":70,"小节":26,"概念":10}[lv]
        ax.scatter([x],[y],s=s,color=color,zorder=2,edgecolors="white",linewidths=0.4)
        txt=n["name"]
        if len(txt)>label_w: txt=txt[:label_w]+"…"
        if lv=="概念":
            ax.text(x+0.06,y,txt,fontproperties=fp,fontsize=fs-2,va="center",ha="left",color="#33475F")
        else:
            ax.text(x+0.06,y,txt,fontproperties=fp,fontsize=fs if lv!="章" else fs+2,
                    va="center",ha="left",fontweight="bold" if lv=="章" else "normal",
                    color=color,bbox=dict(boxstyle="round,pad=0.12",fc="white",ec="none",alpha=0.75))
    ax.set_xlim(-0.2,4.4); ax.invert_yaxis(); ax.axis("off")
    ax.set_title(title,fontproperties=fp,fontsize=13)
    plt.tight_layout()
    p=os.path.join(OUT,fname); fig.savefig(p,dpi=200,bbox_inches="tight",facecolor="white"); plt.close(fig)
    return p,len(pos)

nodes["root"]=dict(id="root",level="章",name="《软件项目管理》")
children["root"]=[f"ch{i}" for i in range(1,11)]
# 总览只到“节”
for ch in range(1,11):
    kids=[c for c in children[f"ch{ch}"] if nodes.get(c,{}).get("level")=="节"]
    children[f"ch{ch}"]=kids
print(draw("root","00-总览-章与节.png","课程知识图谱总览（章—节）",figw=11,fs=9,maxdepth=2))
for ch in range(1,11):
    rid=f"ch{ch}"; nm=nodes[rid]["name"]
    print(draw(rid,f"分章-{ch:02d}-{nm}.png",f"{nm}（章—节—小节—概念）",figw=15,fs=8,maxdepth=9))
