#!/usr/bin/env python3
"""robotics_review.json（データ）から ロボティクス復習.html（声に出して見直すページ）を作る。

使い方（このファイルがある _tools の1つ上のフォルダで）:
    python3 _tools/practice_review.py   # 練習記録があれば先に集計
    python3 _tools/build_review.py

- ページの形は _tools/template.html（仕事で使っている「台本読み合わせ」ページと同じ作り）。データはページの中に埋め込む
- 書き出した ロボティクス復習.html は、GitHub の PixelstoMotors/robotics-review に index.html として置く
  （声を文字にするには https が要るため。公開URL https://pixelstomotors.github.io/robotics-review/）

データの形（items の1件）:
    {"id": "r001", "category": "kinematics", "sub": "小見出し",
     "type": "word" | "lesson",
     "front": "用語 / 場面（問い）", "back": "短い意味 / 教訓（声に出す一言）",
     "detail": "詳しい説明 / 実例（読むだけ）", "kw": [["座標系","座標"],["そろえる","揃える"]]（lesson だけ）,
     "key": true/false, "src": "DAY163"}
    word は「1 単語」（用語＋back を一続きで言う）と「2 説明」（detail を言う）に出る。key は「まず覚える」。
    lesson は「3 判断の型」に出る。場面を見て教訓を自分の言葉で言い、kw の各組から1語ずつ言えていれば合格。key は「核心」。
    id は一度付けたら変えない（ページが「前回の一致」をこの id で覚えている）。新しい項目は末尾の番号の次を付ける。
"""
import json
import sys
from pathlib import Path

ROOT = Path(__file__).resolve().parent.parent
DATA = ROOT / "robotics_review.json"
TEMPLATE = Path(__file__).resolve().parent / "template.html"
OUT = ROOT / "ロボティクス復習.html"
PROGRESS = ROOT / "練習記録_集計.json"  # _tools/practice_review.py が作る（無ければ空）


def src_label(s):
    return "・".join(p.strip() for p in (s or "").split(",") if p.strip())


def build():
    data = json.loads(DATA.read_text(encoding="utf-8"))
    cats = {c["key"] for c in data["categories"]}
    ids = [x.get("id") for x in data["items"]]
    bad = [x.get("id") for x in data["items"]
           if x.get("category") not in cats or x.get("type") not in ("word", "lesson", "point", "term", "qa")
           or not x.get("front") or (x.get("type") != "point" and not x.get("back"))
           or (x.get("type") in ("word", "lesson") and not x.get("detail"))
           or (x.get("type") == "lesson" and not x.get("kw"))]
    if bad:
        sys.exit(f"category / type / front / back が不正な項目: {bad}")
    dup = {i for i in ids if ids.count(i) > 1}
    if dup or None in ids:
        sys.exit(f"id が重複または空: {sorted(i for i in dup if i)}")

    page = {
        "updated": data.get("updated", ""),
        "categories": data["categories"],
        "homophones": data.get("homophones", []),
        "items": [{"id": x["id"], "category": x["category"], "sub": x.get("sub", ""), "type": x["type"],
                   "front": x["front"], "back": x.get("back", ""), "detail": x.get("detail", ""), "key": bool(x.get("key")),
                   "src": src_label(x.get("src")), **({"kw": x["kw"]} if x.get("kw") else {})} for x in data["items"]],
    }
    js = json.dumps(page, ensure_ascii=False, separators=(",", ":")).replace("</", "<\\/")
    html = TEMPLATE.read_text(encoding="utf-8")
    if "/*DATA*/null" not in html:
        sys.exit("template.html に /*DATA*/null が見つかりません")
    prog = json.loads(PROGRESS.read_text(encoding="utf-8")) if PROGRESS.exists() else {}
    pj = json.dumps(prog, ensure_ascii=False, separators=(",", ":")).replace("</", "<\\/")
    if "/*PROGRESS*/{}" not in html:
        sys.exit("template.html に /*PROGRESS*/{} が見つかりません")
    OUT.write_text(html.replace("/*DATA*/null", js).replace("/*PROGRESS*/{}", pj), encoding="utf-8")
    print(f"{OUT.name} を書き出しました（{len(page['items'])}項目・練習記録の集計 {len(prog)}件）")


if __name__ == "__main__":
    build()
