# -*- coding: utf-8 -*-
# 把 ONEBOT 手册 PDF 的系列页拆出渲染成图片 (供目录软件"尺寸图"窗口对照查看)
# 用法:
#   python tools\render-manual-pages.py          # 渲染全部系列
#   python tools\render-manual-pages.py KC       # 只渲染一个系列
# 输出: OnebotCatalog\onebot-data\catalog\manual\<系列>\p<物理页码>.png (灰度 PNG 110dpi, 源目录布局)
import fitz, os, sys

PDF = r"OnebotCatalog\ONEBOT - 直线气缸 - 中文.pdf"
OUT = r"OnebotCatalog\onebot-data\catalog\manual"
DPI = 110

# 系列 → 手册物理页码 (1-based, 含首尾); 依据: 手册印刷页码 = 物理页码 - 1
SERIES_PAGES = {
    "KC":   [2, 3, 4, 5, 6, 11, 12],       # KC 全缸径: 32~125 (p2-6) + 125~320 (p11-12)
    "KCB":  [9, 10],
    "KSB":  [16, 17],
    "KCS":  [13],
    "KS":   [14, 15],
    "KSU":  [14, 15],
    "M":    [22, 23, 24, 25, 26, 27],
    "MS":   [28, 29, 30, 31, 32],
    "MSC":  [33, 34, 35],
    "MAL":  [36, 37, 38, 39, 40],
    "MALC": [41, 42, 43],
}

def main():
    only = sys.argv[1] if len(sys.argv) > 1 else None
    doc = fitz.open(PDF)
    todo = {k: v for k, v in SERIES_PAGES.items()} if only is None else {only: SERIES_PAGES.get(only, [])}
    total = 0
    for series, pages in todo.items():
        if not pages:
            print(f"[warn] 未知系列: {only}")
            continue
        d = os.path.join(OUT, series)
        os.makedirs(d, exist_ok=True)
        for p in pages:
            out = os.path.join(d, f"p{p:02d}.png")
            pix = doc[p - 1].get_pixmap(dpi=DPI, colorspace=fitz.csGRAY)
            pix.save(out)
            kb = os.path.getsize(out) // 1024
            total += kb
            print(f"{series} p{p:02d} -> {kb} KB")
    doc.close()
    print(f"完成, 共 {total // 1024} MB")

if __name__ == "__main__":
    main()
