#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""本地验收：题量、题型、字段、禁用背景、试卷相似度。"""
import re, json, pathlib, sys

ROOT = pathlib.Path(__file__).resolve().parent
EXAM = ROOT / '00_试卷题目指纹.txt'
BANK_DIR = ROOT / '题库分章'
OUT = ROOT / '00_本地验收报告.json'
THRESHOLD = 0.45

BANNED = [
    '交通信号', '交通委', '医学影像', '影像云平台', 'PACS', '跨院调阅', '远程诊断',
    'GSP 合规报表', 'GSP合规报表', '政务云迁移', '信贷审批', '某银行', '仓配调度',
    '波次拣货', '承运商接口', '手持终端', '仓管班组', '医院内网知识库',
    '12 家医院', '12家医院', 'BAC＝800', 'BAC=800', '预算 800 万元', '预算800万元',
    '12 家扩展到 18 家', '12家扩展到18家', 'CR-01', 'CR-02', 'CR-03',
    'PV（累计计划价值）', 'EV（累计挣值）', 'AC（累计实际成本）'
]
PLACEHOLDER_PATTERNS = [
    (r'\bTODO\b', 'TODO'),
    (r'待补', '待补'),
    (r'\[占位', '[占位'),
    (r'<占位', '<占位'),
    (r'(?:^|\n)\s*略\s*(?:$|\n)', '略'),
    (r'[（(]略[）)]', '略'),
    (r'(?:^|\n)\s*……\s*(?:$|\n)', '……'),
]

def norm(s):
    s = s.lower()
    s = re.sub(r'\d+', '#', s)
    s = re.sub(r'[\s\u3000]+', '', s)
    s = re.sub(r'[^\w\u4e00-\u9fff#]', '', s)
    return s

def grams(s, n=3):
    s = norm(s)
    if len(s) < n:
        return {s} if s else set()
    return {s[i:i+n] for i in range(len(s)-n+1)}

def jaccard(a, b):
    ga, gb = grams(a), grams(b)
    if not ga or not gb:
        return 0.0
    return len(ga & gb) / len(ga | gb)

def blocks(text):
    """按 1. / 1、 题号切块。返回 [(number, body)]。"""
    pat = re.compile(r'(?m)^\s*(\d{1,3})[.、]\s*')
    ms = list(pat.finditer(text))
    res = []
    for i, m in enumerate(ms):
        start = m.start()
        end = ms[i+1].start() if i+1 < len(ms) else len(text)
        # 不跨过下一章标题
        nxt = re.search(r'(?m)^#\s', text[m.end():end])
        if nxt:
            end = m.end() + nxt.start()
        res.append((int(m.group(1)), text[start:end].strip()))
    return res

exam_text = EXAM.read_text(encoding='utf-8') if EXAM.exists() else ''
exam_blocks = [b for _, b in blocks(exam_text)]
exam_lines = [l.strip() for l in exam_text.splitlines() if len(l.strip()) >= 8]

chapters = []
flagged = []
banned_hits = []
missing_fields = []
placeholder_hits = []
type_counts = {'选择':0,'填空':0,'判断':0,'问答':0,'案例':0}
total = 0

for i in range(1, 12):
    p = BANK_DIR / f'第{i:02d}章.md'
    if not p.exists():
        chapters.append({'chapter': i, 'file': str(p), 'exists': False, 'count': 0})
        continue
    text = p.read_text(encoding='utf-8')
    bs = blocks(text)
    nums = [n for n, _ in bs]
    count = len(bs)
    total += count
    # 题型按题号区间
    t = {'选择':0,'填空':0,'判断':0,'问答':0,'案例':0}
    for n, _ in bs:
        if 1 <= n <= 20: t['选择'] += 1; type_counts['选择'] += 1
        elif 21 <= n <= 30: t['填空'] += 1; type_counts['填空'] += 1
        elif 31 <= n <= 40: t['判断'] += 1; type_counts['判断'] += 1
        elif 41 <= n <= 45: t['问答'] += 1; type_counts['问答'] += 1
        elif 46 <= n <= 50: t['案例'] += 1; type_counts['案例'] += 1
    # 字段与禁用词
    for n, b in bs:
        for field in ['答案', '解析', '教材依据', '考点']:
            if field not in b:
                missing_fields.append({'chapter': i, 'q': n, 'field': field})
        for pat, label in PLACEHOLDER_PATTERNS:
            if re.search(pat, b, flags=re.M):
                placeholder_hits.append({'chapter': i, 'q': n, 'placeholder': label})
        for kw in BANNED:
            if kw in b:
                banned_hits.append({'chapter': i, 'q': n, 'keyword': kw})
        # 与试卷块相似度
        best, best_idx = 0.0, -1
        for j, eb in enumerate(exam_blocks):
            s = jaccard(b, eb)
            if s > best:
                best, best_idx = s, j
        # 行级精确/近重复提示
        line_hit = ''
        for line in [x.strip() for x in b.splitlines() if len(x.strip()) >= 12][:6]:
            for el in exam_lines:
                if jaccard(line, el) >= 0.75 or norm(line) == norm(el):
                    line_hit = el[:80]
                    break
            if line_hit:
                break
        if best >= THRESHOLD or line_hit:
            flagged.append({
                'chapter': i, 'q': n, 'similarity': round(best, 3),
                'exam_block': exam_blocks[best_idx][:120].replace('\n',' ') if best_idx >= 0 else '',
                'line_hit': line_hit
            })
    chapters.append({
        'chapter': i, 'file': str(p), 'exists': True, 'count': count,
        'numbers_ok': nums == list(range(1, 51)), 'type_counts': t,
        'max_similarity': round(max([f['similarity'] for f in flagged if f['chapter']==i] or [0]), 3)
    })

report = {
    'threshold': THRESHOLD,
    'files_expected': 11,
    'files_found': sum(1 for c in chapters if c.get('exists')),
    'total_questions': total,
    'expected_total': 550,
    'type_counts': type_counts,
    'expected_type_counts': {'选择':220,'填空':110,'判断':110,'问答':55,'案例':55},
    'counts_ok': total == 550 and all(c.get('count') == 50 and c.get('numbers_ok') for c in chapters),
    'chapters': chapters,
    'flagged_similarity': flagged,
    'banned_context_hits': banned_hits,
    'missing_fields': missing_fields,
    'placeholder_hits': placeholder_hits,
}
OUT.write_text(json.dumps(report, ensure_ascii=False, indent=2), encoding='utf-8')
print(json.dumps({
    'files_found': report['files_found'],
    'total_questions': total,
    'type_counts': type_counts,
    'counts_ok': report['counts_ok'],
    'flagged_similarity': len(flagged),
    'banned_context_hits': len(banned_hits),
    'missing_fields': len(missing_fields),
    'placeholder_hits': len(placeholder_hits),
    'report': str(OUT),
}, ensure_ascii=False, indent=2))
