"""
Jedno okno pro výběr kompresní varianty PDF.
Nahoře tlačítka 1–N pro přepínání, tlačítko "Tohle beru" pro potvrzení.
Argumenty: variant_picker.py <json_soubor>
JSON vstup: [{"path": "...", "label": "150 DPI / q80", "size_kb": 139}, ...]
JSON výstup (stdout): {"chosen": "cesta/k/souboru"}
"""
import json
import sys
from pathlib import Path
import tkinter as tk
from PIL import Image, ImageTk
import fitz


def main():
    if len(sys.argv) < 2:
        sys.exit(1)

    variants = json.loads(Path(sys.argv[1]).read_text(encoding="utf-8"))
    chosen = {"path": None}
    docs = [fitz.open(v["path"]) for v in variants]
    current = [0]
    photo_ref = [None]

    root = tk.Tk()
    root.tk.call("encoding", "system", "utf-8")
    root.attributes("-topmost", True)

    sh = root.winfo_screenheight()
    sw = root.winfo_screenwidth()
    win_h = sh - 80   # odečteme taskbar + title bar
    img_h = win_h - 160
    img_w = sw // 2   # šířka okna = polovina monitoru

    x = (sw - img_w) // 2
    root.geometry(f"{img_w}x{win_h}+{x}+0")
    root.resizable(False, False)

    # ── Horní panel s tlačítky variant ──
    frame_top = tk.Frame(root, bg="#222")
    frame_top.pack(fill="x")

    btn_variants = []
    current_page = [0]

    def show(n, page_n=0):
        current[0] = n
        current_page[0] = page_n
        doc = docs[n]
        page = doc[page_n]
        zoom = min(img_w / page.rect.width, img_h / page.rect.height)
        pix = page.get_pixmap(matrix=fitz.Matrix(zoom, zoom))
        img = Image.frombytes("RGB", (pix.width, pix.height), pix.samples)
        photo_ref[0] = ImageTk.PhotoImage(img)
        lbl_img.config(image=photo_ref[0])
        page_count = len(doc)
        root.title(f"Varianta {n+1}: {variants[n]['label']}  ({variants[n]['size_kb']} kB)  —  strana {page_n+1}/{page_count}")
        for i, b in enumerate(btn_variants):
            b.config(bg="#2a5a9a" if i == n else "#444")
        btn_prev_page.config(state="normal" if page_n > 0 else "disabled")
        btn_next_page.config(state="normal" if page_n < page_count - 1 else "disabled")

    for i, v in enumerate(variants):
        b = tk.Button(
            frame_top,
            text=f"{i+1}. {v['label']}\n{v['size_kb']} kB",
            font=("Segoe UI", 9, "bold"),
            bg="#444", fg="white",
            relief="flat", padx=8, pady=6,
            command=lambda n=i: show(n),
        )
        b.pack(side="left", padx=2, pady=4)
        btn_variants.append(b)

    # ── Tlačítka Beru / Přeskočit — stejný styl jako varianty ──
    def beru():
        chosen["path"] = variants[current[0]]["path"]
        root.destroy()

    def preskocit():
        root.destroy()

    tk.Button(
        frame_top,
        text="✓ Tohle beru\n",
        command=beru,
        bg="#2a7a2a", fg="white",
        font=("Segoe UI", 9, "bold"),
        relief="flat", padx=8, pady=6,
    ).pack(side="left", padx=2, pady=4)

    tk.Button(
        frame_top,
        text="✗ Přeskočit\n",
        command=preskocit,
        bg="#7a2a2a", fg="white",
        font=("Segoe UI", 9, "bold"),
        relief="flat", padx=8, pady=6,
    ).pack(side="left", padx=2, pady=4)

    # ── Navigace stran — úplně vpravo ──
    btn_next_page = tk.Button(
        frame_top,
        text="Další ►\n",
        command=lambda: show(current[0], current_page[0] + 1),
        bg="#555", fg="white",
        font=("Segoe UI", 9, "bold"),
        relief="flat", padx=8, pady=6,
    )
    btn_next_page.pack(side="right", padx=2, pady=4)

    btn_prev_page = tk.Button(
        frame_top,
        text="◄ Před.\n",
        command=lambda: show(current[0], current_page[0] - 1),
        bg="#555", fg="white",
        font=("Segoe UI", 9, "bold"),
        relief="flat", padx=8, pady=6,
    )
    btn_prev_page.pack(side="right", padx=2, pady=4)

    # ── Obrázek ──
    lbl_img = tk.Label(root, bg="black")
    lbl_img.pack(fill="both", expand=True)

    root.bind("<Key-1>", lambda e: show(0))
    root.bind("<Key-2>", lambda e: show(1))
    root.bind("<Key-3>", lambda e: show(2))
    root.bind("<Key-4>", lambda e: show(3))
    root.bind("<Key-5>", lambda e: show(4))
    root.bind("<Return>", lambda e: beru())
    root.bind("<Escape>", lambda e: preskocit())

    show(0)
    root.lift()
    root.focus_force()
    root.after(100, lambda: root.focus_force())
    root.after(200, lambda: root.attributes("-topmost", True))
    root.mainloop()

    for d in docs:
        try:
            d.close()
        except Exception:
            pass

    print(json.dumps({"chosen": chosen["path"]}, ensure_ascii=False))


if __name__ == "__main__":
    main()
