"""
Ukázka 2 puzzle vedle sebe na A4 — varianty 93 % (mezera 10 pt) a 89 % (mezera 20 pt).
Výsledek: 2stránkové PDF.
"""

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_puzzles.pdf")

A4_W = 595.276
A4_H = 841.890
CROP_MARGIN = 2


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 add_page(doc_out, doc_src, clip, gap_pt):
    scale = (A4_W - 3 * gap_pt) / 2 / clip.width
    pw = clip.width  * scale
    ph = clip.height * scale
    y0 = (A4_H - ph) / 2  # vertikálně vycentrovat

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

    for i in range(2):
        x0 = gap_pt + i * (pw + gap_pt)
        page.show_pdf_page(fitz.Rect(x0, y0, x0 + pw, y0 + ph), doc_src, 0, clip=clip)

    pct = scale * 100
    label = (f"mezera {gap_pt:.0f} pt  |  měřítko {pct:.0f} %  |  "
             f"puzzle {pw:.0f} × {ph:.0f} pt  =  {pw/72*25.4:.0f} × {ph/72*25.4:.0f} mm")
    page.insert_text((30, 25), label, fontsize=9, color=(0.4, 0.4, 0.4))


def main():
    doc_src = fitz.open(str(SRC))
    clip = detect_clip(doc_src[0])
    print(f"Oříznutý puzzle: {clip.width:.1f} × {clip.height:.1f} pt")

    doc_out = fitz.open()
    for gap in (10, 20):
        add_page(doc_out, doc_src, clip, gap)
        scale = (A4_W - 3 * gap) / 2 / clip.width
        print(f"  gap={gap} pt -> meritko {scale*100:.0f} %  puzzle {clip.width*scale:.0f}x{clip.height*scale:.0f} pt")

    doc_out.save(str(DST))
    doc_src.close()
    doc_out.close()
    print(f"\nUloženo: {DST}")


if __name__ == "__main__":
    main()
