"""ブックの印刷の設定を、シートごとに並べて出す。

使い方:
    python print-check.py ブック.xlsx

出るもの:
    用紙と向き、余白、拡大縮小の指定、印刷範囲、繰り返す行と列、手で入れた改ページの数。
    配る前に全部のシートを見て、印刷範囲の消し忘れや、縦も1ページの指定を見つける。

Python 3.9 以降。openpyxl が要る。
"""

from __future__ import annotations

import sys

try:
    from openpyxl import load_workbook
except ImportError:
    print("openpyxl が要る。pip install openpyxl で入れる")
    raise SystemExit(2)

PAPER = {1: "レター", 8: "A3", 9: "A4", 11: "A5", 12: "B4", 13: "B5"}


def cm(points) -> str:
    """openpyxl の余白はインチ。センチに直す。"""
    if points is None:
        return "既定"
    return "%.1fcm" % (float(points) * 2.54)


def main(argv: list[str]) -> int:
    if len(argv) < 2:
        print(__doc__)
        return 2
    try:
        sys.stdout.reconfigure(encoding="utf-8")
    except Exception:
        pass
    wb = load_workbook(argv[1])
    warn = []
    for ws in wb.worksheets:
        ps = ws.page_setup
        pr = ws.sheet_properties.pageSetUpPr
        fit = bool(pr and pr.fitToPage)
        paper = PAPER.get(ps.paperSize, str(ps.paperSize) if ps.paperSize else "既定")
        muki = "横" if ps.orientation == "landscape" else "縦"
        print(ws.title)
        print("  用紙 %s %s / 余白 上%s 下%s 左%s 右%s"
              % (paper, muki, cm(ws.page_margins.top), cm(ws.page_margins.bottom),
                 cm(ws.page_margins.left), cm(ws.page_margins.right)))
        if fit:
            # 既定の1は xml に書かれないので、無いときは1として読む。0は自動の意味
            wide = 1 if ps.fitToWidth is None else int(ps.fitToWidth)
            tall = 1 if ps.fitToHeight is None else int(ps.fitToHeight)
            print("  拡大縮小 横%s 縦%s"
                  % ("自動" if wide == 0 else "%dページ" % wide,
                     "自動" if tall == 0 else "%dページ" % tall))
            if tall != 0:
                warn.append("%s は縦も%dページに収める指定。行が増えると字が小さくなる"
                            % (ws.title, tall))
            if ps.scale:
                print("  Excelが計算した縮小率 %s%%" % ps.scale)
                if int(ps.scale) < 70:
                    warn.append("%s の縮小率が%s%%まで下がっている。紙で読めるか確かめる"
                                % (ws.title, ps.scale))
        else:
            z = ps.scale or 100
            print("  拡大縮小 %s%%" % z)
            if int(z) < 70:
                warn.append("%s の縮小率が%s%%。紙で読めるか確かめる" % (ws.title, z))
        print("  印刷範囲 %s" % (ws.print_area or "なし"))
        if ws.print_area:
            warn.append("%s に印刷範囲が残っている（%s）" % (ws.title, ws.print_area))
        print("  繰り返す行 %s / 繰り返す列 %s"
              % (ws.print_title_rows or "なし", ws.print_title_cols or "なし"))
        rb = len(ws.row_breaks.brk) if ws.row_breaks else 0
        cb = len(ws.col_breaks.brk) if ws.col_breaks else 0
        print("  手で入れた改ページ 横%d か所 / 縦%d か所" % (rb, cb))
        if rb + cb > 0:
            warn.append("%s に改ページが%d か所ある。行を足すと位置がずれる"
                        % (ws.title, rb + cb))
        dim = ws.calculate_dimension()
        print("  値の入っている範囲 %s" % dim)
        if not ws.print_title_rows and ws.max_row > 60:
            warn.append("%s は%d行あるのに繰り返す行がない。2枚目から見出しが消える"
                        % (ws.title, ws.max_row))
        print("")
    if warn:
        print("見るところ")
        for wline in warn:
            print("  " + wline)
    else:
        print("見るところ なし")
    return 0


if __name__ == "__main__":
    raise SystemExit(main(sys.argv))
