#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""更严格查重：只比对题干 + 选项 + 答案/参考答案要点，不含解析。

算法与 check_sim.py 相同：去标点、数字归一后做字符 3-gram Jaccard。
对照 00_试卷题目指纹.txt 与 00_试卷原文_供查重.txt。
"""
from __future__ import annotations

import json
import re
import sys
from pathlib import Path

sys.path.insert(0, str(Path(__file__).resolve().parent))
from check_sim import (  # noqa: E402
    jaccard,
    load_exam_items,
    normalize,
)

ROOT = Path(__file__).resolve().parents[1]
BANK = ROOT / "题库分章"
EXAM = [
    ROOT / "00_试卷题目指纹.txt",
    ROOT / "00_试卷原文_供查重.txt",
]


def stimulus(block: str) -> str:
    """题干、选项、答案要点。解析、教材依据、考点不进入比对。"""
    m = re.search(r"\*\*答案：\*\*|\*\*参考答案：\*\*", block)
    if not m:
        return block
    head = block[: m.end()]
    tail = block[m.end() :]
    tail = re.split(r"\*\*解析：\*\*", tail, maxsplit=1)[0]
    return (head + tail).strip()


def parse_questions(md: str) -> list[dict]:
    parts = re.split(r"\n(?=\d{1,2}\.\s)", "\n" + md)
    qs = []
    for p in parts:
        m = re.match(r"(\d{1,2})\.\s", p)
        if not m:
            continue
        n = int(m.group(1))
        if 1 <= n <= 50:
            qs.append({"n": n, "text": stimulus(p.strip())})
    return qs


def main():
    items = load_exam_items(EXAM)
    rows = []
    global_max = 0.0
    global_hits = []
    for i in range(1, 12):
        path = BANK / f"第{i:02d}章.md"
        md = path.read_text(encoding="utf-8")
        qs = parse_questions(md)
        hits = []
        chapter_max = 0.0
        best_n = 0
        for q in qs:
            best = 0.0
            best_item = ""
            for it in items:
                s = jaccard(q["text"], it)
                if s > best:
                    best = s
                    best_item = it
            if best > chapter_max:
                chapter_max = best
                best_n = q["n"]
            if best >= 0.45:
                hit = {
                    "chapter": i,
                    "n": q["n"],
                    "sim": round(best, 4),
                    "exam": best_item.replace("\n", " ")[:160],
                    "q": q["text"].replace("\n", " ")[:160],
                }
                hits.append(hit)
                global_hits.append(hit)
        global_max = max(global_max, chapter_max)
        rows.append(
            {
                "chapter": i,
                "q_count": len(qs),
                "max_sim": round(chapter_max, 4),
                "best_n": best_n,
                "hit_count": len(hits),
            }
        )
        print(
            f"ch{i:02d} q={len(qs)} max={chapter_max:.4f} q{best_n} hits>={0.45}={len(hits)}"
        )
    print(f"GLOBAL_MAX {global_max:.4f}")
    print(f"HITS {len(global_hits)}")
    out = {
        "scope": "题干+选项+答案要点",
        "threshold": 0.45,
        "global_max": round(global_max, 4),
        "hit_count": len(global_hits),
        "chapters": rows,
        "hits": global_hits,
    }
    dest = ROOT / "_tools" / "strict_sim.json"
    dest.write_text(json.dumps(out, ensure_ascii=False, indent=2), encoding="utf-8")
    print(dest)


if __name__ == "__main__":
    main()
