# =============================================================================
# 한자도장(net.birdlab.hanja) 획순 데이터 변환 스크립트 — 공개용 사본
# 원본: 저장소 tools/content/own_strokes.py (커밋 0d2b8af, 2026-10-08, strokes_version 4). 내용은 원본 그대로이며
#       import 경로(tools.content.lib…)도 원본 저장소 구조를 따른다. 원천 데이터 경로는 tools/content/lib/paths.py 기준
#       (hanzi-writer-data/data/*.json, kanjivg-20260714.xml).
# 만든 파일과 라이선스:
#   strokes_mmh.db — Make Me a Hanzi 그래픽의 수정본(바이너리 변환 + 자체 작도 91자, src="own").
#                    Arphic Public License 조건에 따라 수정본과 변환 방법(이 스크립트)을 같은 라이선스로 자유 제공한다.
#   이 파일은 자체 작도 레시피(own_strokes_recipes.json)를 Make Me a Hanzi 부품 획에 적용한다 — Arphic Public License.
# 데이터 출처:
#   Make Me a Hanzi graphics © 2016 Shaunak Kishore, based on fonts by Arphic Technology Co., Ltd. © 1999
#   (hanzi-writer-data, https://github.com/chanind/hanzi-writer-data) — Arphic Public License (APL.txt)
#   KanjiVG © Ulrich Apel, released under the Creative Commons Attribution-Share Alike 3.0 licence
#   (https://kanjivg.tagaini.net/) — CC BY-SA 3.0 (CC-BY-SA-3.0-kanjivg.txt)
# 공개 위치: https://hanja-site.silverbird-dev.workers.dev/data/
# =============================================================================
"""자체 작도: Hanzi Writer(MMH) 데이터에 없는 8급~1급 51자를 MMH 부품 조합 레시피로 만든다(스펙 §6-5 5, 한국 분할).

  own_strokes.py --preview <ch>…   → build/review/own/<ch>.png (조합 윤곽·필순 번호 / Noto Serif KR / 겹쳐 그리기)
  own_strokes.py --sheet           → build/review/own51.png (51행: 조합 윤곽 | Noto Serif KR | 획수·IoU)
  own_strokes.py --hw <ch>…        → build/review/own/hw_<ch>.png (HW 원본 글자에 획 번호 — 레시피 작성용)
  own_strokes.py --report          → 글자별 IoU 표 출력

레시피 manual/own_strokes/<ch>.json:
  {"ch", "korean_strokes", "note", "parts": [{"from": HW 글자, "strokes": [획 번호…], "affine": [a,b,c,d,e,f]}…], "rad_strokes": […],
   "split_diff"?: true, "override"?: true}
  override = HW·KanjiVG 획순이 있는 글자를 한국 정자 자형으로 다시 짠 레시피(Task 20 V15 교정) — strokes.py 가 원천 행을 대신한다.
  획 순서 = parts 순서대로 이어 붙임. affine: x' = a·x + c·y + e, y' = b·x + d·y + f (윤곽 제어점·median 모두, 글리프 공간).
"""
import argparse
import colorsys
import json
import sys
from pathlib import Path

if __package__ in (None, ""):  # 스크립트로 실행: 저장소 루트를 sys.path에 추가
    sys.path.insert(0, str(Path(__file__).resolve().parents[2]))

from tools.content import strokes  # noqa: E402
from tools.content.lib import paths, raster, svgpath  # noqa: E402

RECIPES = paths.MANUAL / "own_strokes"
REVIEW = paths.BUILD / "review"
NOTO_KR = paths.FONTS_DIR / "NotoSerifKR[wght].ttf"
IOU_SIZE, IOU_DILATE = 128, 6


def load_recipes(recipe_dir=None) -> dict:
    """{글자: 레시피} — 파일 이름 = 글자, 정렬 순서."""
    d = Path(recipe_dir or RECIPES)
    out = {}
    for p in sorted(d.glob("*.json")) if d.exists() else []:
        rec = json.loads(p.read_text(encoding="utf-8"))
        if rec["ch"] != p.stem:
            raise ValueError(f"{p.name}: ch {rec['ch']!r} != 파일 이름")
        out[rec["ch"]] = rec
    return out


def _tx(aff, x, y):
    a, b, c, d, e, f = aff
    return a * x + c * y + e, b * x + d * y + f


def transform_path(d: str, aff) -> str:
    """HW 윤곽 path(절대 M L Q C Z) 의 모든 좌표에 affine 적용 → 정수 반올림(floor(v + 0.5)) path 문자열."""
    out = []
    for cmd, args in svgpath.parse_outline(d):
        out.append(cmd)
        for k in range(0, len(args), 2):
            x, y = _tx(aff, args[k], args[k + 1])
            out += [str(strokes.q(x)), str(strokes.q(y))]
    return " ".join(out)


def transform_median(pts, aff) -> list:
    return [[strokes.q(v) for v in _tx(aff, x, y)] for x, y in pts]


def apply(recipe) -> tuple:
    """레시피 → (outline_paths, medians, rad_strokes). 각 part 의 HW 획을 affine 변환해 parts 순서로 이어 붙인다."""
    outline, medians = [], []
    for part in recipe["parts"]:
        hw = strokes.load_hw(part["from"])
        if hw is None:
            raise ValueError(f"{recipe['ch']}: HW 데이터에 {part['from']!r} 없음")
        aff = part["affine"]
        if len(aff) != 6:
            raise ValueError(f"{recipe['ch']}: affine 은 6개 수")
        for i in part["strokes"]:
            outline.append(transform_path(hw["strokes"][i], aff))
            medians.append(transform_median(hw["medians"][i], aff))
    rad = list(recipe.get("rad_strokes") or [])
    if any(not 0 <= i < len(medians) for i in rad):
        raise ValueError(f"{recipe['ch']}: rad_strokes {rad} 가 획 수 {len(medians)} 범위 밖")
    for s in medians:
        for x, y in s:
            if not (strokes.X_MIN <= x <= strokes.X_MAX and strokes.Y_MIN <= y <= strokes.Y_MAX):
                raise ValueError(f"{recipe['ch']}: median 좌표 ({x}, {y}) 가 글리프 공간 밖")
    return outline, medians, rad


def own_rows(recipe_dir=None) -> list:
    """strokes_mmh.db 행(src="own", modified_note = 레시피 note)."""
    rows = []
    for ch, rec in load_recipes(recipe_dir).items():
        outline, medians, rad = apply(rec)
        rows.append(dict(ch=ch, count=len(medians), outline=strokes.encode_outline(outline), median=strokes.encode_median(medians),
                         rad_strokes=",".join(str(i) for i in rad), src="own", modified_note=rec["note"], override=bool(rec.get("override"))))
    return rows


def iou_one(ch, outline) -> float:
    return raster.iou(raster.outline_mask(outline, size=IOU_SIZE, dilate=IOU_DILATE),
                      raster.glyph_mask(NOTO_KR, ch, size=IOU_SIZE, dilate=IOU_DILATE))


def iou_report(recipe_dir=None) -> dict:
    """{글자: IoU(조합 윤곽, Noto Serif KR wght500 글리프)} — 둘 다 128px 래스터, 6px 팽창(해서·명조 굵기 차 흡수)."""
    return {ch: round(iou_one(ch, apply(rec)[0]), 4) for ch, rec in load_recipes(recipe_dir).items()}


# ── 검수 그림 ─────────────────────────────────────────────────────────────

def _colors(n):
    return [tuple(int(255 * v) for v in colorsys.hsv_to_rgb(0.75 * i / max(n - 1, 1), 0.85, 0.85)) for i in range(n)]


def numbered(outline, medians, size=320, ch_bg=None):
    """획마다 색(필순 = 빨강 → 보라)·시작점 번호(1부터)를 넣은 RGB 이미지. ch_bg 면 Noto 글리프를 옅게 깐다."""
    from PIL import Image, ImageDraw
    import numpy as np
    img = Image.new("RGB", (size, size), (255, 255, 255))
    if ch_bg:
        g = raster.glyph_mask(NOTO_KR, ch_bg, size=size)
        arr = np.asarray(img).copy()
        arr[g] = (215, 215, 215)
        img = Image.fromarray(arr)
    d = ImageDraw.Draw(img, "RGBA")
    cols = _colors(len(outline))
    for k, (path, col) in enumerate(zip(outline, cols)):
        for poly in raster._flatten(svgpath.parse_outline(path)):
            d.polygon([raster._px(x, y, size) for x, y in poly], fill=col + (150,), outline=col + (255,))
    font = raster._label_font(max(12, size // 22))
    for k, (pts, col) in enumerate(zip(medians, cols)):
        line = [raster._px(x, y, size) for x, y in pts]
        d.line(line, fill=(0, 0, 0, 160), width=1)
        x0, y0 = line[0]
        d.ellipse([x0 - 3, y0 - 3, x0 + 3, y0 + 3], fill=(0, 0, 0, 255))
        d.text((x0 + 3, y0 - size // 22 - 2), str(k + 1), fill=(0, 0, 0, 255), font=font)
    return img


def preview(ch, recipe=None, out=None) -> Path:
    from PIL import Image, ImageDraw
    import numpy as np
    rec = recipe or load_recipes()[ch]
    outline, medians, _ = apply(rec)
    size = 320
    left = numbered(outline, medians, size)
    mid = Image.fromarray(np.where(raster.glyph_mask(NOTO_KR, ch, size=size)[..., None], 30, 255).astype("uint8").repeat(3, axis=2))
    over = numbered(outline, medians, size, ch_bg=ch)
    sheet = Image.new("RGB", (3 * size + 4 * 8, size + 16 + 34), (255, 255, 255))
    for i, im in enumerate((left, mid, over)):
        sheet.paste(im, (8 + i * (size + 8), 8))
    n = len(medians)
    ImageDraw.Draw(sheet).text((8, size + 14), f"{ch}  {n}획 (한국 {rec['korean_strokes']}획)  IoU {iou_one(ch, outline):.3f}",
                               fill=(0, 0, 0), font=raster._label_font(22))
    out = Path(out or REVIEW / "own" / f"{ch}.png")
    out.parent.mkdir(parents=True, exist_ok=True)
    sheet.save(out)
    return out


def hw_preview(ch, out=None) -> Path:
    hw = strokes.load_hw(ch)
    if hw is None:
        raise SystemExit(f"HW 데이터에 {ch} 없음")
    img = numbered(hw["strokes"], hw["medians"], 320)
    out = Path(out or REVIEW / "own" / f"hw_{ch}.png")
    out.parent.mkdir(parents=True, exist_ok=True)
    img.save(out)
    return out


def make_sheet(out=None) -> Path:
    rows = []
    for ch, rec in load_recipes().items():
        outline, medians, _ = apply(rec)
        rows.append((numbered(outline, medians, raster.CELL), raster.glyph_mask(NOTO_KR, ch, size=raster.CELL),
                     f"{ch}  {len(medians)}획 / 한국 {rec['korean_strokes']}획\nIoU {iou_one(ch, outline):.3f}"
                     + ("  split_diff" if rec.get("split_diff") else "")))
    return raster.sheet(rows, out or REVIEW / "own51.png")


def main(argv=None) -> int:
    ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    ap.add_argument("--preview", nargs="+", metavar="CH")
    ap.add_argument("--hw", nargs="+", metavar="CH")
    ap.add_argument("--sheet", action="store_true")
    ap.add_argument("--report", action="store_true")
    args = ap.parse_args(argv)
    for s in args.preview or []:
        for ch in s:
            print(preview(ch))
    for s in args.hw or []:
        for ch in s:
            print(hw_preview(ch))
    if args.sheet:
        print(make_sheet())
    if args.report:
        for ch, v in iou_report().items():
            print(f"{ch}\t{v:.3f}")
    return 0


if __name__ == "__main__":
    sys.exit(main())
