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

import fitz
from pathlib import Path
import os

BASE_DIR = Path(r"u:\Dropbox\Ordinace\Dokumentace_ke_zpracování\EKGforProcessing")

FLAG = "rotated-by-script"

for pdf_path in BASE_DIR.glob("*.pdf"):
    print(f"Processing: {pdf_path.name}")

    doc = fitz.open(pdf_path)

    meta = doc.metadata
    keywords = meta.get("keywords", "") or meta.get("Keywords", "") or ""

    # ---- Check if already processed ----
    if FLAG in keywords:
        print("   → Already rotated, skipping.")
        doc.close()
        continue

    try:
        # ---- Rotate first page ----
        first = doc[0]
        first.set_rotation((first.rotation + 90) % 360)

        # ---- Delete page 2 (if exists) ----
        if doc.page_count > 1:
            doc.delete_page(1)

        # ---- Update metadata Keywords ----
        new_keywords = (keywords + " " + FLAG).strip()
        meta["keywords"] = new_keywords
        doc.set_metadata(meta)

        # ---- Save via temporary file ----
        tmp_path = pdf_path.with_suffix(".tmp.pdf")
        doc.save(tmp_path, deflate=True, garbage=3)
        doc.close()

        os.replace(tmp_path, pdf_path)

        print("   → Rotated & marked.")

    except Exception as e:
        print(f"❌ Error: {e}")
        doc.close()

print("Done.")
