"""女子学院の解答 PDF (出版社作成, 「弊社が作成」と明記) のテキスト層を復号して data/official_answers.json に入れる。
学校公表の正解ではないため source_kind = "publisher" とし、画面では『学校公表の正解: なし (出版社作成の解答)』と表示する。
文字化け記号の復号表 (目視で確定): 宗=1. 就=2. 州=3. 修=4. 愁=5. 拾=6. 洲=7. / 唄=(1) 欝=(2) 蔚=(3) 鰻=(4) 姥=(5) 厩=(6) 浦=(7) / 或=cm² 安=cm³ 粟=【不明記号】
自動解読は配置 (列) の崩れで誤る可能性があるため needs_check=True を付け、教材作成時に解答PDFの画像と照合する。
"""
from __future__ import annotations
import re, fitz
from common import *

BIG = {"宗": 1, "就": 2, "州": 3, "修": 4, "愁": 5, "拾": 6, "洲": 7}
SUB = {"唄": 1, "欝": 2, "蔚": 3, "鰻": 4, "姥": 5, "厩": 6, "浦": 7}
UNIT = {"或": "cm²", "安": "cm³", "粟": "【不明記号】"}
Z2H = str.maketrans("０１２３４５６７８９．，：", "0123456789.,:")

def tokens(doc):
    out = []
    for pg in doc:
        for b in pg.get_text("dict")["blocks"]:
            if b["type"] != 0: continue
            for l in b["lines"]:
                for s in l["spans"]:
                    t = s["text"].strip()
                    if t: out.append((pg.number, s["bbox"], t))
    return out

def parse(doc):
    """トークン列を順に読み、大問/小問の切り替え記号で分配する。戻り値: {Q01: {S01: '...'}}, 警告"""
    toks = tokens(doc)
    q, s_ = 0, 0
    answers = {}
    warnings = []
    buf = []
    def flush():
        nonlocal buf
        if q and buf:
            key_q = f"Q{q:02d}"; key_s = f"S{max(s_,1):02d}"
            txt = " ".join(buf).strip()
            txt = "".join(UNIT.get(ch, ch) for ch in txt).translate(Z2H)
            answers.setdefault(key_q, {})
            answers[key_q][key_s] = (answers[key_q].get(key_s, "") + " " + txt).strip()
        buf = []
    for pgno, bbox, t in toks:
        if t in BIG:
            flush(); q, s_ = BIG[t], 0; continue
        if t in SUB:
            flush(); s_ = SUB[t]
            if q == 0: q = 1
            continue
        m = re.fullmatch(r"[１-７1-7]", t)
        # 旧年度: 全角数字 1 文字が大問番号 (左端にある). 小問記号の直後でなく、かつ次が小問記号/①/値なら大問とみなす
        if m and bbox[0] < 80 and (t in "１２３４５６７" ):
            n = int(t.translate(Z2H))
            if n == q + 1:
                flush(); q, s_ = n, 0; continue
        if "解答" == t or t.startswith("上記の解答") or "女子学院中学校" in t or "年度" in t or t.startswith("- ") or t in ("（算数）", "(算数)", "解答と解説"):
            continue
        buf.append(t)
    flush()
    return answers, warnings

def main():
    exams = load_json(DATA / "exams.json")["exams"]
    sources = {s["source_id"]: s for s in load_json(DATA / "sources.json")["sources"]}
    off = load_json(DATA / "official_answers.json", {"exams": {}})
    n = 0
    for e in exams:
        if e["school_code"] != "JG": continue
        sid = e["answer_sheet_source_ids"][0] if e["answer_sheet_source_ids"] else None
        if not sid: continue
        src = sources[sid]
        doc = fitz.open(ROOT / src["rel_path"])
        ans, warns = parse(doc)
        # 解説付きの年度 (2007〜2012) は解答ページだけを使う: 「解説」以降を除くのは困難なので、1ページ目のみ採用し注記
        if len(doc) > 1:
            ans, warns = parse(fitz.open(ROOT / src["rel_path"]))  # 全ページを読むが、長い解説文は値として混入し得る
        existing = off["exams"].get(e["exam_id"], {})
        if existing.get("transcribed_by") == "agent_visual":
            continue  # 目視転記済みは上書きしない
        off["exams"][e["exam_id"]] = {
            "source_id": sid, "page_index": 0, "transcribed_by": "auto_decode_publisher_pdf", "transcribed_at": now_iso()[:10],
            "source_kind": "publisher", "scoring_note": "配点の記載なし (出版社作成の解答)",
            "answers": ans, "needs_check": True,
            "notes": "出版社作成の解答 (PDF 末尾に『上記の解答は，弊社が作成致しました。』)。学校公表の正解ではない。文字化け記号を復号表で自動解読したため、教材作成時に画像と照合すること。" + (" 解説を含むPDF。" if len(doc) > 1 else "")}
        n += 1
    save_json(DATA / "official_answers.json", off)
    print("JG answers decoded:", n)
    for e in exams:
        if e["school_code"] == "JG" and e["year"] >= 2024:
            print(e["exam_id"], json.dumps(off["exams"][e["exam_id"]]["answers"], ensure_ascii=False)[:600])

if __name__ == "__main__":
    import json
    main()
