"""
2 puzzle na A4 — 100 %, pod sebou, horizontálně vycentrované.
Místo vlevo/vpravo zůstává pro poznámky.
"""

import fitz
from pathlib import Path

SRC = Path(r"U:/ordinaceprojekt/SběrDatRůzné/DailySudokuKiller/Testy/2009-05-04 Puzzle SudokuKiller 376 [difficulty 4 of 10] [average solving time 30 min].pdf")
DST = Path(r"U:/ordinaceprojekt/SběrDatRůzné/DailySudokuKiller/Testy/two_vertical_110.pdf")

A4_W = 595.276
A4_H = 841.890
CROP_MARGIN = 2
SCALE = 1.10


def detect_clip(page) -> fitz.Rect:
    paths = page.get_drawings()
    y_mid = page.mediabox.height / 2
    hit_h = [(p["rect"], p.get("width") or 0) for p in paths
             if p["rect"].y0 <= y_mid <= p["rect"].y1]
    rects = [r for r, _ in hit_h]
    x_left  = min(r.x0 for r in rects)
    x_right = max(r.x1 for r in rects)
    top_cut = min(r.y0 for r in rects)
    bot_cut = max(r.y1 for r in rects)
    lw_l = next((lw for r, lw in hit_h if r.x0 == x_left),  0)
    lw_r = next((lw for r, lw in hit_h if r.x1 == x_right), 0)
    return fitz.Rect(
        x_left  - lw_l / 2 - CROP_MARGIN,
        top_cut - CROP_MARGIN,
        x_right + lw_r / 2 + CROP_MARGIN,
        bot_cut + CROP_MARGIN,
    )


def main():
    doc_src = fitz.open(str(SRC))
    clip = detect_clip(doc_src[0])
    pw = clip.width  * SCALE
    ph = clip.height * SCALE

    # Horizontální pozice — vycentrovat na A4
    x0 = (A4_W - pw) / 2

    # Vertikální rozdělení: 3 mezery (nahoře, mezi, dole)
    gap = (A4_H - 2 * ph) / 3
    y_top = gap
    y_bot = gap + ph + gap

    side_space = x0  # místo vlevo/vpravo pro poznámky

    print(f"Puzzle: {pw:.1f} x {ph:.1f} pt  ({pw/72*25.4:.0f} x {ph/72*25.4:.0f} mm)")
    print(f"Meritko: {SCALE*100:.0f} %")
    print(f"Misto vlevo/vpravo: {side_space:.1f} pt  ({side_space/72*25.4:.0f} mm)")
    print(f"Mezera mezi puzzle: {gap:.1f} pt  ({gap/72*25.4:.0f} mm)")

    doc_out = fitz.open()
    page = doc_out.new_page(width=A4_W, height=A4_H)

    for y0_pos in (y_top, y_bot):
        page.show_pdf_page(
            fitz.Rect(x0, y0_pos, x0 + pw, y0_pos + ph),
            doc_src, 0,
            clip=clip,
        )

    doc_out.save(str(DST))
    doc_src.close()
    doc_out.close()
    print(f"Ulozeno: {DST}")


if __name__ == "__main__":
    main()
