# -*- 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(7)
a,c=bp.load_all(); P=bp.assemble(a,c); A=P["1A"]

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

def txt(it): return it.get("stem") or it.get("background") or ""
def norm(s): return re.sub(r"[（(].*?[)）]","",re.sub(r"\s+","",s or ""))
A_norm=[norm(txt(x)) for x in A]
A_ids={id(x) for x in A}
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)
for x in A: plan[x["type"]][x["chapter"]]+=1
diff_target=defaultdict(Counter)
for x in A: 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 not sim_any(it,[norm(txt(x)) for x in B]) and not sim_any(it,A_norm)]
        random.shuffle(cands)
        # 先按难度缺口优先
        cur=Counter(x["difficulty"] for x in B if x["type"]==t)
        for need_d,w in sorted(diff_target[t].items(), key=lambda kv:-(diff_target[t][kv[0]]-cur[kv[0]])):
            pick=[it for it in cands if it["difficulty"]==need_d][: max(0,min(n-len([x for x in B if x['type']==t and x['chapter']==ch]), 1))]
            for it in pick:
                if it not in B and len([x for x in B if x["type"]==t and x["chapter"]==ch])<n:
                    B.append(it); cands.remove(it)
        # 补齐
        for it in cands:
            if len([x for x in B if x["type"]==t and x["chapter"]==ch])>=n: break
            if it not in B: B.append(it)

print("B",len(B),Counter(x["type"] for x in B))
print("章",Counter(x["chapter"] for x in B))
print("难度",Counter(x["difficulty"] for x in B))
print("目标难度",dict(diff_target))
json.dump(B,open("b_items.json","w",encoding="utf-8"),ensure_ascii=False,indent=1)

# —— 难度平衡：把多出的“难”换成缺的“中”（同题型同章）——
def bal():
    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]
                cand=[x for x in B if x["type"]==t and x["difficulty"]==od]
                swapped=False
                for x in cand:
                    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,[norm(txt(y)) for y in B if y is not x])
                          and not sim_any(it,A_norm)]
                    if repl:
                        B.remove(x); B.append(repl[0]); cur[od]-=1; cur[need]+=1; swapped=True; break
                if not swapped: break
bal()
print("平衡后 难度",Counter(x["difficulty"] for x in B))
print("平衡后 总数",len(B))
json.dump(B,open("b_items.json","w",encoding="utf-8"),ensure_ascii=False,indent=1)
