# -*- coding: utf-8 -*-
"""步骤6 题卡机器核查：字段/槽位/查重/泄题/背景/计算一致性。"""
import re,pathlib,json,itertools

root=pathlib.Path('.')
exam=pathlib.Path('../../30-复习大纲与题库/00_试卷题目指纹.txt').read_text(encoding='utf-8')
exam2=pathlib.Path('../../30-复习大纲与题库/00_试卷原文_供查重.txt').read_text(encoding='utf-8')

BANNED=['医学影像','PACS','政务云','信贷审批','仓配调度','波次拣货','交通信号','GSP 合规','GSP合规','CR-01','CR-02','CR-03','BAC=800','BAC＝800','12 家医院','12家医院','20 人天','30 人天','8 人天']
NOTE= ['与试卷不同','不要求默写','故意不用','不使用其他','不采用某情境','与试卷第','避开试卷']

def norm(s):
    s=s.lower(); s=re.sub(r'\d+','0',s); s=re.sub(r'[\s\u3000]+','',s)
    return re.sub(r'[^\w\u4e00-\u9fff0]','',s)
def g3(s,n=3):
    s=norm(s); return {s[i:i+n] for i in range(len(s)-n+1)} if len(s)>=n else ({s} if s else set())
def jac(a,b):
    A,B=g3(a),g3(b)
    return len(A&B)/len(A|B) if A and B else 0.0

def cards(path):
    t=pathlib.Path(path).read_text(encoding='utf-8')
    parts=re.split(r'(?m)^### 题卡编号：', t)
    out=[]
    for p in parts[1:]:
        cid=p.split('\n',1)[0].strip()
        out.append((cid,p))
    return t,out

exam_units=[x for x in re.split(r'\n(?=\d+[、.])', exam+'\n'+exam2) if len(x.strip())>20]

rep={'A':{}, 'B':{}}
for vol,f in (('A','06-A卷题卡.md'),('B','06-B卷题卡.md')):
    t,cs=cards(f)
    info={'n':len(cs),'banned':[],'notes':[],'max_sim':0.0,'sim_hi':[],'fill_leak':[],'bg':{},'missing':[]}
    fill_answers=[]
    for cid,body in cs:
        for w in BANNED:
            if w in body: info['banned'].append((cid,w))
        for w in NOTE:
            if w in body: info['notes'].append((cid,w))
        for fld in ['| 编号 |','| 章 |','| 知识点 |','| 题型 |','| 难度 |','| 认知层次 |','| 答案 |','| 解析 |','| 教材依据 |','| 考点 |','| 状态 |','| 课程目标 |','| 页码 |','| 对应细目槽位 |']:
            if fld not in body: info['missing'].append((cid,fld.strip()))
        m=re.search(r'\| 背景名称 \| ([^|]+)\|', body)
        if m:
            bg=m.group(1).strip()
            if bg and bg!='无': info['bg'][bg]=info['bg'].get(bg,0)+1
        if '-FB-' in cid:
            m2=re.search(r'\| 答案 \| ([^|]+)\|', body)
            if m2: fill_answers += [x.strip() for x in re.split(r'[；;，,]', m2.group(1)) if x.strip()]
        # 相似度
        stem=body
        for unit in exam_units:
            s=jac(stem,unit)
            if s>info['max_sim']: info['max_sim']=s
            if s>=0.45: info['sim_hi'].append((cid,round(s,3)))
    # 填空答案出现在选择选项
    for cid,body in cs:
        if '-MC-' in cid:
            opts=re.findall(r'^[A-D][.．、]\s*(.+)$', body, re.M)
            for fa in fill_answers:
                for o in opts:
                    if fa and fa in o: info['fill_leak'].append((cid,fa,o[:30]))
    rep[vol]=info

out=pathlib.Path('06-机器核查.json'); out.write_text(json.dumps(rep,ensure_ascii=False,indent=2),encoding='utf-8')
for v,i in rep.items():
    print(f"== {v} 卷: 卡 {i['n']} | 禁用词 {len(i['banned'])} | 出题备忘 {len(i['notes'])} | 缺字段 {len(i['missing'])} | 最高相似 {i['max_sim']:.4f} | ≥0.45 {len(i['sim_hi'])} | 填空答案入选项 {len(i['fill_leak'])}")
    if i['bg']: print('   背景计数:', dict(sorted(i['bg'].items(), key=lambda x:-x[1])[:6]))
print('报告:', out)
