#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Compress a PDF into multiple variants at different DPI / JPEG quality settings.
Uses PyMuPDF (fitz) — renders each page as JPEG image, saves back as PDF.
"""

import sys
import fitz  # PyMuPDF
from pathlib import Path

INPUT = Path(r"u:\Medevio\50 Různé testy\MinimizeOptimizePDF\afd1823b-8277-44a2-84e1-db89a0ccd134.pdf")
OUT_DIR = INPUT.parent

VARIANTS = [
    # (label,  dpi, jpeg_quality)
    ("300dpi_q90",  300, 90),
    ("200dpi_q85",  200, 85),
    ("150dpi_q80",  150, 80),
    ("120dpi_q75",  120, 75),
    ("96dpi_q70",    96, 70),
    ("72dpi_q60",    72, 60),
]

src = fitz.open(INPUT)
original_size = INPUT.stat().st_size
print(f"Originál: {INPUT.name}  ({original_size / 1024:.0f} KB)\n")
print(f"{'Varianta':<20} {'DPI':>5} {'Kvalita':>8} {'Velikost':>12} {'Úspora':>8}")
print("-" * 58)

for label, dpi, quality in VARIANTS:
    out_path = OUT_DIR / f"{INPUT.stem}_{label}.pdf"
    zoom = dpi / 72.0
    mat = fitz.Matrix(zoom, zoom)

    out_doc = fitz.open()
    for page in src:
        pix = page.get_pixmap(matrix=mat, colorspace=fitz.csRGB)
        img_bytes = pix.tobytes("jpeg", jpg_quality=quality)

        # Create a new PDF page with the same physical dimensions
        img_doc = fitz.open("pdf", fitz.open("jpeg", img_bytes).convert_to_pdf())
        # Scale page back to original size
        rect = page.rect
        new_page = out_doc.new_page(width=rect.width, height=rect.height)
        new_page.show_pdf_page(new_page.rect, img_doc, 0)

    out_doc.save(out_path, deflate=True, garbage=4)
    out_doc.close()

    size = out_path.stat().st_size
    size_kb = round(size / 1024)
    final_path = OUT_DIR / f"{INPUT.stem}_{label} ({size_kb} kB).pdf"
    out_path.rename(final_path)

    saving = (1 - size / original_size) * 100
    print(f"{label:<20} {dpi:>5} {quality:>8} {size_kb:>9} kB {saving:>7.0f}%")

src.close()
print("\nHotovo.")
