# -*- coding: utf-8 -*-
"""设计 B 卷：与 A 卷题不重复、知识点尽量错开、难度结构一致"""
import sys, json, random, re
sys.path.insert(0,".")
import build_papers as bp
from difflib import SequenceMatcher
from collections import Counter

random.seed(20261114)

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):
    s=re.sub(r"\s+","",s or "")
    s=re.sub(r"[（(].*?[)）]","",s)
    return s

def sim(x,y):
    return SequenceMatcher(None,x,y).ratio()

A_norm=[norm(txt(x)) for x in A]
A_ids={id(x) for x in A}

def clash(it, chosen):
    s=norm(txt(it))
    for x in A_norm:
        if sim(s,x)>=0.8: return True
    for x in chosen:
        if sim(s,norm(txt(x)))>=0.8: return True
    return False

need=Counter((x["type"],x["chapter"],x["difficulty"]) for x in A)
items=[v for v in pool.values() if id(v) not in A_ids]

# 可用候选中先按“填空题两空”过滤
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

chosen=[]
for (t,ch,diff),n in sorted(need.items()):
    cands=[it for it in items if it["type"]==t and it["chapter"]==ch and it["difficulty"]==diff and ok(it,t) and not clash(it,chosen)]
    random.shuffle(cands)
    # 先挑关键节点与 A 不同的
    for it in cands:
        if len([x for x in chosen if x["type"]==t and x["chapter"]==ch and x["difficulty"]==diff])>=n: break
        if not clash(it,chosen):
            chosen.append(it)

print("选中",len(chosen),Counter(x["type"] for x in chosen))
print("章",Counter(x["chapter"] for x in chosen))
print("难",Counter(x["difficulty"] for x in chosen))
json.dump(chosen,open("b_items.json","w",encoding="utf-8"),ensure_ascii=False,indent=1)
