# -*- 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-知识图谱"
os.makedirs(OUT,exist_ok=True)

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)

def tidy(root):
    """返回 {id:(x,y,depth)} 与叶子数"""
    pos={}
    def rec(nid,depth):
        ch=[c for c in children.get(nid,[]) if c in nodes]
        if not ch:
            pos[nid]=(0,depth); return 1
        w=0; xs=[]
        for c in ch:
            cw=rec(c,depth+1); xs.append((w,w+cw-1)); w+=cw
        for c,(a,b) in zip(ch,xs):
            pass
        x=(xs[0][0]+xs[-1][1])/2 if xs else 0
        pos[nid]=(x,depth)
        return w
    total=rec(root,0)
    return pos,total

def draw(root_id, fname, title, figw=16, figh=10, fs=7, rot=45):
    pos,total=tidy(root_id)
    xs=[p[0] for p in pos.values()]; ys=[p[1] for p in pos.values()]
    fig,ax=plt.subplots(figsize=(figw,figh))
    maxd=max(ys) if ys else 1
    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="#B8C4D9",lw=0.6,zorder=1)
    for nid,(x,y) in pos.items():
        n=nodes[nid]; lv=n["level"]
        color={"章":"#1F3B63","节":"#2E5C8A","小节":"#5B8FC9","概念":"#9DB8D9"}[lv]
        size={"章":260,"节":120,"小节":45,"概念":12}[lv]
        ax.scatter([x],[-y],s=size,color=color,zorder=2,edgecolors="white",linewidths=0.4)
        name=n["name"]
        if lv in ("章","节","小节"):
            ax.text(x,-y-0.08,name,fontproperties=fp,fontsize=fs+1 if lv=="章" else fs,
                    ha="center",va="top",rotation=0,zorder=3,
                    bbox=dict(boxstyle="round,pad=0.15",fc="white",ec="none",alpha=0.85))
        else:
            ax.text(x,-y-0.05,name,fontproperties=fp,fontsize=fs-0.5,ha="left",va="top",
                    rotation=rot,rotation_mode="anchor",color="#33475F",zorder=3)
    ax.set_title(title,fontproperties=fp,fontsize=14)
    ax.axis("off")
    ax.set_ylim(-maxd-1.2,0.8)
    plt.tight_layout()
    p=os.path.join(OUT,fname)
    fig.savefig(p,dpi=220,bbox_inches="tight",facecolor="white")
    plt.close(fig)
    return p,len(pos)

# 总览：课程→章→节
# 造一个虚拟根
nodes["root"]=dict(id="root",level="章",name="《软件项目管理》知识图谱",chapter=0)
children["root"]=[f"ch{i}" for i in range(1,11)]
print(draw("root","00-总览-章与节.png","《软件项目管理》知识图谱总览（章—节，共 10 章）",figw=22,figh=9,fs=6.5,rot=90))

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=18,figh=11,fs=6.5,rot=40))
