"""
Standalone dialog pro schválení / opravu názvu souboru.
Spouští se jako subprocess z extract_patient_info.py.
Argumenty: rename_dialog.py <json_soubor>
JSON vstup:  { "nazev": "...", "info_lines": [...] }
JSON výstup: { "value": "..." }  nebo  { "value": null }
"""
import json
import os
import sys
from pathlib import Path
import tkinter as tk

if sys.platform == "win32":
    try:
        from ctypes import windll
        windll.shcore.SetProcessDpiAwareness(1)
    except Exception:
        pass
    import io
    sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding="utf-8", errors="replace")
    sys.stderr = io.TextIOWrapper(sys.stderr.buffer, encoding="utf-8", errors="replace")


def main():
    if len(sys.argv) < 2:
        print(json.dumps({"value": None}))
        sys.exit(0)

    data = json.loads(Path(sys.argv[1]).read_text(encoding="utf-8"))
    nazev = data.get("nazev") or ""
    info_lines = data.get("info_lines") or []

    result = {"value": None}

    root = tk.Tk()
    root.title("Schválení názvu souboru")
    root.resizable(True, False)
    root.attributes("-topmost", True)

    pad = {"padx": 12, "pady": 6}

    frame_info = tk.Frame(root, bg="#f0f0f0", bd=1, relief="sunken")
    frame_info.pack(fill="x", **pad)
    for line in info_lines:
        color = "#b00000" if line.startswith("⚠") else "#004080" if line.startswith("✓") else "#333"
        tk.Label(frame_info, text=line, anchor="w", bg="#f0f0f0",
                 fg=color, font=("Segoe UI", 10)).pack(fill="x", padx=8, pady=1)

    tk.Label(root, text="Název souboru (bez .pdf):", anchor="w",
             font=("Segoe UI", 9, "bold")).pack(fill="x", padx=12, pady=(10, 2))

    nazev_bez = nazev[:-4] if nazev.endswith(".pdf") else nazev
    var = tk.StringVar(value=nazev_bez)
    entry = tk.Entry(root, textvariable=var, font=("Segoe UI", 10), width=135)
    entry.pack(fill="x", padx=12, pady=(0, 10))
    entry.icursor(tk.END)
    entry.focus_set()

    frame_btn = tk.Frame(root)
    frame_btn.pack(pady=(0, 12))

    def schvalit(event=None):
        result["value"] = var.get().strip()
        root.destroy()

    def preskocit(event=None):
        result["value"] = None
        root.destroy()

    tk.Button(frame_btn, text="✓  Schválit  (Enter)", command=schvalit,
              bg="#2a7a2a", fg="white", font=("Segoe UI", 10, "bold"),
              padx=16, pady=6).pack(side="left", padx=8)
    tk.Button(frame_btn, text="✗  Přeskočit  (Esc)", command=preskocit,
              bg="#7a2a2a", fg="white", font=("Segoe UI", 10),
              padx=16, pady=6).pack(side="left", padx=8)

    root.bind("<Return>", schvalit)
    root.bind("<Escape>", preskocit)

    root.update_idletasks()
    sw = root.winfo_screenwidth()
    w = root.winfo_width()
    h = root.winfo_height()
    x = (sw - w) // 2

    # Skutečná použitelná výška (bez taskbaru)
    import ctypes, ctypes.wintypes
    rect = ctypes.wintypes.RECT()
    ctypes.windll.user32.SystemParametersInfoW(48, 0, ctypes.byref(rect), 0)
    work_bottom = rect.bottom  # spodní hrana work area

    # Pozice pod preview oknem pokud byl předán argument --below-y=N
    below_y = None
    for arg in sys.argv:
        if arg.startswith("--below-y="):
            below_y = int(arg.split("=", 1)[1])
            break

    if below_y is not None and below_y + h + 10 <= work_bottom:
        y = below_y  # vejde se pod preview
    else:
        y = max(0, work_bottom - h - 10)  # přilepit těsně nad taskbar
    root.geometry(f"+{x}+{y}")

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

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


if __name__ == "__main__":
    main()
