# -*- coding: utf-8 -*-
import sys,json,re
sys.path.insert(0,".")
import build_papers as bp
from difflib import SequenceMatcher
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

def norm(s): return re.sub(r"\s+","",s or "")
def txt(it): return (it.get("stem") or "")+"".join(it.get("options") or [])

new_q16=dict(pool["3CQ16"]); new_q16["slot"]="Q16"
new_s1=dict(pool["1CS1"]); new_s1["slot"]="S1"

new_t3={"slot":"T3","type":"tf","chapter":5,"difficulty":"中","points":1,
 "stem":"滚动式规划要求项目一开始就把全部活动完整定义清楚，以免后续反复补充。（   ）",
 "answer":"×",
 "explain":"滚动式规划是渐进明细的体现：近期要开展的工作详细规划，远期工作只做粗略规划，随项目推进逐步细化，而不是一次性定义全部活动。",
 "kp":"5.3.1 定义活动的方法；滚动式规划"}

new_f8={"slot":"F8","type":"fill","chapter":5,"difficulty":"难","points":2,
 "stem":"通过增加资源、以增加成本换取工期缩短的进度压缩方式称为（1）______；通过并行搭接、以返工风险换取工期缩短的方式称为（2）______。",
 "answers":["赶工","快速跟进"],
 "explain":"赶工通过增加人力、加班或加设备压缩关键活动历时，代价是成本上升；快速跟进把本应串行的活动并行开展，代价是返工与协调风险上升。两者都只能作用于关键路径上的活动才有效。",
 "kp":"5.6.1 制订进度计划的方法；进度压缩（赶工与快速跟进）"}

out=[]
for it in A:
    if it["slot"]=="Q16": out.append(new_q16)
    elif it["slot"]=="S1": out.append(new_s1)
    elif it["slot"]=="T3": out.append(new_t3)
    elif it["slot"]=="F8": out.append(new_f8)
    else: out.append(it)

# S3 术语按教材：评价成本
for it in out:
    if it["slot"]=="S3":
        it["answer"]=it["answer"].replace("评估成本（鉴定成本）","评价成本（鉴定成本）")
        it["kp"]="7.2.1 规划质量管理的方法；质量成本（一致性成本与非一致性成本）"

# 排重：新题与其余题相似度
bad=[]
for x in out:
    for y in out:
        if x is y: continue
        r=SequenceMatcher(None,norm(txt(x)),norm(txt(y))).ratio()
        if r>=0.8: bad.append((x["slot"],y["slot"],round(r,2)))
print("similar pairs",bad[:5])
json.dump(out,open("a_items.json","w",encoding="utf-8"),ensure_ascii=False,indent=1)
from collections import Counter
print(len(out),Counter(x["type"] for x in out),Counter(x["difficulty"] for x in out),sum(int(x["points"]) for x in out))
