#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import fitz  # PyMuPDF
import os
from pathlib import Path

# ===============================
# 📁 FOLDER SETTINGS
# ===============================
input_folder = Path(r"u:\Dropbox\Ordinace\Dokumentace_ke_zpracování\A4 expand")
output_suffix = "_A4scaled.pdf"

# A4 portrait size in points
A4_WIDTH, A4_HEIGHT = 595, 842

# ===============================
# ⚙️ FUNCTION
# ===============================
def normalize_to_A4_portrait(pdf_path: Path):
    output_path = pdf_path.with_name(pdf_path.stem + output_suffix)

    # skip if already exists
    if output_path.exists():
        try:
            output_path.unlink()
            print(f"🧹 Deleted old: {output_path.name}")
        except PermissionError:
            print(f"⚠️ Skipped {output_path.name} (open elsewhere)")
            return

    src = fitz.open(pdf_path)
    dst = fitz.open()
    changed = False

    for i, page in enumerate(src, 1):
        rect = page.rect
        w, h = rect.width, rect.height

        # check if already close to A4 size (within 2%)
        if abs(w - A4_WIDTH) < 12 and abs(h - A4_HEIGHT) < 17:
            # copy directly without change
            dst.insert_pdf(src, from_page=i - 1, to_page=i - 1)
            print(f"✅ {pdf_path.name} page {i}: already A4, copied as-is.")
            continue

        changed = True
        scale = min(A4_WIDTH / w, A4_HEIGHT / h)
        new_w, new_h = w * scale, h * scale

        # horizontal center, vertical TOP
        x_off = (A4_WIDTH - new_w) / 2
        y_off = 0  # 👈 place at top edge

        new_page = dst.new_page(width=A4_WIDTH, height=A4_HEIGHT)
        new_page.show_pdf_page(
            fitz.Rect(x_off, y_off, x_off + new_w, y_off + new_h),
            src,
            page.number
        )

        print(f"📄 {pdf_path.name} page {i}: {w:.0f}×{h:.0f} → {new_w:.0f}×{new_h:.0f} (top-aligned)")

    dst.save(output_path)
    src.close()
    dst.close()

    if changed:
        print(f"✅ Saved normalized A4 PDF: {output_path.name}\n")
    else:
        print(f"➡️ No change needed: {pdf_path.name}\n")


# ===============================
# 🚀 MAIN LOOP
# ===============================
for file in input_folder.glob("*.pdf"):
    normalize_to_A4_portrait(file)

print("\n🎉 All PDFs processed — scaled to A4 portrait, top-aligned.")
