# -*- coding: utf-8 -*-
import json,re,sys
sys.path.insert(0,".")
import build_papers as bp
from collections import Counter,defaultdict

g=json.load(open("kg2.json",encoding="utf-8"))
nodes={n["id"]:n for n in g["nodes"]}
kids=defaultdict(list); parent={}
for a,b in g["edges"]:
    kids[a].append(b); parent[b]=a

def norm(s):
    s=re.sub(r"^\d+(\.\d+)*\s*","",s)
    s=re.sub(r"[（(].*?[)）]","",s)
    return re.sub(r"[\s　]","",s)

secs=[n for n in g["nodes"] if n["level"]=="节"]
subs=[n for n in g["nodes"] if n["level"]=="小节"]
cons=[n for n in g["nodes"] if n["level"]=="概念"]

def text_of(it):
    t=(it.get("kp","") or "")+" "+(it.get("stem","") or "")+" ".join(it.get("options") or [])
    if it.get("type")=="fill": t+=" "+" ".join(it.get("answers") or [])
    if it.get("type")=="case":
        t+=" "+(it.get("background","") or "")
        for q in it.get("questions",[]): t+=" "+q["q"]
    return t

def cover(items):
    cs=set(); cu=set(); ck=set()
    for it in items:
        tn=norm(text_of(it))
        for n in subs:
            if n["chapter"]!=it["chapter"]: continue
            nm=norm(n["name"])
            if len(nm)>=4 and nm in tn: cu.add(n["id"])
        for n in secs:
            if n["chapter"]!=it["chapter"]: continue
            nm=norm(n["name"])
            if len(nm)>=4 and nm in tn: cs.add(n["id"])
        for num in re.findall(r"(\d+\.\d+(?:\.\d+)?)", it.get("kp","") or ""):
            for n in subs+secs:
                if n["chapter"]==it["chapter"] and n["name"].startswith(num):
                    (cu if n["level"]=="小节" else cs).add(n["id"])
        for n in cons:
            if n["chapter"]!=it["chapter"]: continue
            nm=norm(n["name"])
            if len(nm)>=3 and nm in tn: ck.add(n["id"])
        # 概念 -> 上级
        for cid in list(ck):
            p=parent.get(cid)
            if p: (cu if nodes[p]["level"]=="小节" else cs).add(p)
        for sid in list(cu):
            p=parent.get(sid); cs.add(p)
        for sid in list(cs):
            for c in kids.get(sid,[]):
                if nodes[c]["level"]=="小节": cu.add(c)
    return cs,cu,ck

a,c=bp.load_all(); P=bp.assemble(a,c)
cs,cu,ck=cover(P["1A"])
u_s,u_u,u_k=set(),set(),set()
for pid,its in P.items():
    x,y,z=cover(its); u_s|=x; u_u|=y; u_k|=z

def pct(a,b): return f"{len(a)}/{b}（{len(a)/b*100:.1f}%）"
print("1A 节",pct(cs,len(secs)),"小节",pct(cu,len(subs)),"概念",pct(ck,len(cons)))
print("12 节",pct(u_s,len(secs)),"小节",pct(u_u,len(subs)),"概念",pct(u_k,len(cons)))
print("\n分章（1A）：")
for ch in range(1,11):
    s0=[n["id"] for n in secs if n["chapter"]==ch]; u0=[n["id"] for n in subs if n["chapter"]==ch]
    k0=[n["id"] for n in cons if n["chapter"]==ch]
    print(f"第{ch}章 节{len(set(s0)&cs)}/{len(s0)} 小节{len(set(u0)&cu)}/{len(u0)} 概念{len(set(k0)&ck)}/{len(k0)}")
miss=[n["name"] for n in subs if n["id"] not in cu]
print("\n未覆盖小节",len(miss)); print("；".join(miss[:60]))
json.dump({"cs":sorted(cs),"cu":sorted(cu),"ck":sorted(ck),"u_s":sorted(u_s),"u_u":sorted(u_u),"u_k":sorted(u_k)},
          open("cover1a2.json","w",encoding="utf-8"),ensure_ascii=False)
