"""
Ořízne vzorový puzzle (ray-cast) a vygeneruje jedno PDF s 7 stránkami A4,
každá stránka ukazuje puzzle zmenšený o 10–70 % (krok 10 %).
"""

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

A4_W = 595.276
A4_H = 841.890
MARGIN = 2  # pt bílý rámeček kolem puzzlu po ořezu


def detect_clip(page) -> fitz.Rect:
    paths = page.get_drawings()
    ph = page.mediabox.height
    y_mid = ph / 2

    hit_h = [(p["rect"], p.get("width") or 0) for p in paths
             if p["rect"].y0 <= y_mid <= p["rect"].y1]
    if not hit_h:
        raise ValueError("Detekce hranic selhala")

    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_left  = next((lw for r, lw in hit_h if r.x0 == x_left),  0)
    lw_right = next((lw for r, lw in hit_h if r.x1 == x_right), 0)

    return fitz.Rect(
        x_left  - lw_left  / 2 - MARGIN,
        top_cut - MARGIN,
        x_right + lw_right / 2 + MARGIN,
        bot_cut + MARGIN,
    )


def main():
    doc_src = fitz.open(str(SRC))
    page_src = doc_src[0]
    clip = detect_clip(page_src)

    puzzle_w = clip.width
    puzzle_h = clip.height
    print(f"Oříznutý puzzle: {puzzle_w:.1f} × {puzzle_h:.1f} pt")

    doc_out = fitz.open()

    scales = [0.10, 0.20, 0.30, 0.40, 0.50, 0.60, 0.70]

    for scale in scales:
        pw = puzzle_w * scale
        ph = puzzle_h * scale

        # Vycentrovat na A4
        x0 = (A4_W - pw) / 2
        y0 = (A4_H - ph) / 2

        page = doc_out.new_page(width=A4_W, height=A4_H)
        page.show_pdf_page(
            fitz.Rect(x0, y0, x0 + pw, y0 + ph),
            doc_src, 0,
            clip=clip,
        )

        pct = int(scale * 100)
        label = f"{pct} %  ({pw:.0f} × {ph:.0f} pt  =  {pw/72*25.4:.0f} × {ph/72*25.4:.0f} mm)"
        page.insert_text((30, 30), label, fontsize=11, color=(0.4, 0.4, 0.4))
        print(f"  Stránka {pct}%: puzzle {pw:.0f}×{ph:.0f} pt ({pw/72*25.4:.0f}×{ph/72*25.4:.0f} mm)")

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


if __name__ == "__main__":
    main()
