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

g=json.load(open("kg2.json",encoding="utf-8")); nodes={n["id"]:n for n in g["nodes"]}
secs=[n for n in g["nodes"] if n["level"]=="节"]; subs=[n for n in g["nodes"] if n["level"]=="小节"]
def norm(s): return re.sub(r"[（(].*?[)）]","",re.sub(r"\s+","",s or ""))
def txt(it): return it.get("stem") or it.get("background") or ""
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 secs_of(it):
    tn=norm(text_of(it)); out=set()
    for n in subs:
        if n["chapter"]==it["chapter"] and "实验" not in n["name"]:
            nm=norm(n["name"])
            if len(nm)>=4 and nm in tn: out.add(n["id"])
    for num in re.findall(r"(\d+\.\d+(?:\.\d+)?)", it.get("kp","")):
        for n in subs:
            if n["chapter"]==it["chapter"] and n["name"].startswith(num): out.add(n["id"])
    return out

a,c=bp.load_all(); P=bp.assemble(a,c); A=P["1A"]
A_sec=set()
for x in A: A_sec|=secs_of(x)
A_norm=[norm(txt(x)) for x in A]; A_ids={id(x) for x in A}

pool={}
for cid in c:
    for k,v in c[cid]["shared"].items(): pool[f"{cid}S{k}"]=v
    for pid,pp in c[cid]["papers"].items():
        for k,v in pp["unique"].items(): pool[f"{pid}{k}"]=v
for k,v in a.items(): pool[f"A{k}"]=v

# 练习题库补充（第1—7章）
try:
    bank=json.load(open("bank_1_7.json",encoding="utf-8"))
    for i,x in enumerate(bank):
        t=x["type"]
        if t not in ("single","tf","fill"): continue
        it=dict(slot=f"P{i}",type=t,chapter=int(x["chapter"]),difficulty=x["difficulty"],
                stem=x["stem"],options=x.get("options") or [],
                answer=x["answer"],explain=x.get("explain",""),kp=x.get("kp",""))
        if t=="tf":
            it["answer"]="√" if x["answer"] in ("对","√","正确") else "×"; it["points"]=1
        elif t=="fill":
            ans=[a.strip() for a in str(x["answer"]).split("；") if a.strip()]
            if len(ans)!=2: continue
            it["answers"]=ans; it["answer"]="；".join(ans); it["points"]=2
        else:
            it["points"]=1
        pool[f"BANK{i}"]=it
except FileNotFoundError:
    pass
items=[v for v in pool.values() if id(v) not in A_ids]

def sim_any(it, seq):
    s=norm(txt(it))
    return any(SequenceMatcher(None,s,t).ratio()>=0.8 for t in seq)
def ok(it,t):
    if t=="fill" and len(it.get("answers") or [])!=2: return False
    if t=="single" and len(it.get("options") or [])!=4: return False
    return True

plan=defaultdict(Counter); diff_target=defaultdict(Counter)
for x in A: plan[x["type"]][x["chapter"]]+=1; diff_target[x["type"]][x["difficulty"]]+=1

B=[]
for t in ("single","fill","tf","short","case"):
    for ch,n in sorted(plan[t].items()):
        cands=[it for it in items if it["type"]==t and it["chapter"]==ch and ok(it,t) and it not in B
               and not sim_any(it,A_norm) and not sim_any(it,[norm(txt(x)) for x in B])]
        # 新知识点优先
        cands.sort(key=lambda it: (-len(secs_of(it)-A_sec), random.random()))
        take=cands[:n]
        B.extend(take)

# 难度平衡
for t in ("single","fill","tf","short","case"):
    tar=Counter(diff_target[t]); cur=Counter(x["difficulty"] for x in B if x["type"]==t)
    for need in ("中","易","难"):
        while cur[need]<tar[need]:
            over=[d for d in ("难","中","易") if cur[d]>tar[d] and d!=need]
            if not over: break
            od=over[0]; done=False
            for x in [y for y in B if y["type"]==t and y["difficulty"]==od]:
                repl=[it for it in items if it["type"]==t and it["chapter"]==x["chapter"] and it["difficulty"]==need
                      and it not in B and ok(it,t) and not sim_any(it,A_norm)
                      and not sim_any(it,[norm(txt(y)) for y in B if y is not x])]
                if repl:
                    B.remove(x); B.append(repl[0]); cur[od]-=1; cur[need]+=1; done=True; break
            if not done: break

print("B",len(B),Counter(x["type"] for x in B),Counter(x["difficulty"] for x in B))
print("章",sorted(Counter(x["chapter"] for x in B).items()))
B_sec=set()
for x in B: B_sec|=secs_of(x)
print("小节覆盖 A",len(A_sec),"B",len(B_sec),"重叠",len(A_sec&B_sec),"新",len(B_sec-A_sec))
json.dump(B,open("b_items.json","w",encoding="utf-8"),ensure_ascii=False,indent=1)
