# -*- coding: utf-8 -*-
"""build_hwpx 산출(양식 native 190x260mm, 본문폭 35150)을 A4 폭(42520)으로 상향 보정.
finalize_layout.mjs 는 입력을 A4(42520) 본문으로 가정하고 native(35150)로 재축소하므로,
그림 임베드 단계를 생략할 때 이 보정을 거쳐야 이중 축소가 없다.
(메모리 gdi-hwpx-figure-table-finalize 절차의 표 부분만 — 이미지 없음)

사용: python a4_upconvert.py <in.hwpx> <out.hwpx>
"""
import re
import shutil
import sys
import zipfile

SRC_W = 35150
DST_W = 42520
F = DST_W / SRC_W


def main(inp, outp):
    shutil.copyfile(inp, outp)
    with zipfile.ZipFile(inp) as z:
        sec = z.read("Contents/section0.xml").decode("utf-8")

    # 1) secPr -> A4 (59528x84189, 좌우 8504=30mm, 상 5669=20mm, 머리말/꼬리말/하 4252=15mm)
    def fix_pagepr(m):
        s = m.group(0)
        s = re.sub(r'width="\d+"', 'width="59528"', s, count=1)
        s = re.sub(r'height="\d+"', 'height="84189"', s, count=1)
        return s

    before_page = re.search(r"<hp:pagePr[^>]*>", sec)
    sec = re.sub(r"<hp:pagePr[^>]*>", fix_pagepr, sec, count=1)

    def fix_margin(m):
        s = m.group(0)
        s = re.sub(r'left="\d+"', 'left="8504"', s)
        s = re.sub(r'right="\d+"', 'right="8504"', s)
        s = re.sub(r'top="\d+"', 'top="5669"', s)
        s = re.sub(r'header="\d+"', 'header="4252"', s)
        s = re.sub(r'footer="\d+"', 'footer="4252"', s)
        s = re.sub(r'bottom="\d+"', 'bottom="4252"', s)
        return s

    sec = re.sub(r"<hp:margin[^>]*/>", fix_margin, sec, count=1)

    # 2) 표 고정폭 + 폭 스케일업 (35150 -> 42520)
    n_tbl = len(re.findall(r"<hp:tbl\b", sec))
    sec = re.sub(r'(<hp:tbl\b[^>]*noAdjust=")0(")', r"\g<1>1\g<2>", sec)
    sec = re.sub(
        r'(<hp:tbl\b[^>]*>\s*<hp:sz width=")(\d+)(")',
        lambda m: m.group(1) + str(round(int(m.group(2)) * F)) + m.group(3),
        sec,
    )
    n_cell = 0

    def sc_cell(m):
        nonlocal n_cell
        n_cell += 1
        return '<hp:cellSz width="%d" height="%s"/>' % (round(int(m.group(1)) * F), m.group(2))

    sec = re.sub(r'<hp:cellSz width="(\d+)" height="(\d+)"/>', sc_cell, sec)

    # zip 갱신
    import os

    tmp = outp + ".tmp"
    with zipfile.ZipFile(inp) as zin, zipfile.ZipFile(tmp, "w", zipfile.ZIP_DEFLATED) as zout:
        for item in zin.infolist():
            if item.filename == "Contents/section0.xml":
                zout.writestr(item, sec.encode("utf-8"))
            elif item.filename == "mimetype":
                zout.writestr(item, zin.read(item.filename), zipfile.ZIP_STORED)
            else:
                zout.writestr(item, zin.read(item.filename))
    os.replace(tmp, outp)
    print("OK: pagePr %s / tbl %d개 / cellSz %d개 스케일(x%.4f)" % ("교체" if before_page else "미발견", n_tbl, n_cell, F))


if __name__ == "__main__":
    main(sys.argv[1], sys.argv[2])
