#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""事实抽查：把练习题里出现的数字（年份/百分比/公式常数/金额），逐一到讲稿原文里比对。
用法：python3 factcheck.py <练习题.md> <讲稿.md>
输出：数字 token 总数，以及未在讲稿中找到的题号与 token（人工复核是否编造）。
说明：'1.【单选题】' 里的题号不计；答案行不计（答案只是字母）。
"""
import re, sys

NUM_RE = re.compile(r'\d+(?:\.\d+)?(?:%|％)?')


def norm(s):
    return (s.replace('（', '(').replace('）', ')').replace('，', ',')
             .replace('％', '%').replace(' ', '').replace('\u3000', '')
             .replace('$', '').replace('×', ''))


def main(md, src):
    text = norm(open(src, encoding='utf-8').read())
    lines = open(md, encoding='utf-8').read().splitlines()
    blocks, cur = [], None
    for ln in lines:
        m = re.match(r'^\s*(\d+)\.【(单选题|判断题)】(.*)$', ln)
        if m:
            cur = {'no': int(m.group(1)), 'text': m.group(3)}
            blocks.append(cur)
            continue
        if cur is None:
            continue
        if ln.startswith('答案：'):
            continue
        cur['text'] += ln
    total, missing = 0, []
    for b in blocks:
        nums = set(NUM_RE.findall(norm(b['text'])))
        total += len(nums)
        nf = sorted(n for n in nums if n not in text)
        if nf:
            missing.append((b['no'], nf))
    print(f'文件：{md}')
    print(f'  数字 token {total} 个，未命中 {sum(len(x[1]) for x in missing)} 个')
    for no, nf in missing:
        print(f'  第{no}题：{nf}')
    return 0


if __name__ == '__main__':
    sys.exit(main(sys.argv[1], sys.argv[2]))
