import os
import subprocess
import tkinter as tk
from tkinter import filedialog, messagebox, scrolledtext
from pathlib import Path

class MarkdownToPDFApp:
    def __init__(self, root):
        self.root = root
        self.root.title("Markdown → PDF Converter")
        self.root.geometry("600x400")
        self.root.resizable(False, False)

        self.folder_path = tk.StringVar()
        self.output_name = tk.StringVar(value="manuale.pdf")

        # --- UI ---
        tk.Label(root, text="Cartella Markdown:").pack(anchor="w", padx=10, pady=(10,0))
        frame1 = tk.Frame(root)
        frame1.pack(fill="x", padx=10)
        tk.Entry(frame1, textvariable=self.folder_path, width=50).pack(side="left", fill="x", expand=True)
        tk.Button(frame1, text="Sfoglia...", command=self.choose_folder).pack(side="right", padx=5)

        tk.Label(root, text="Nome file PDF finale:").pack(anchor="w", padx=10, pady=(10,0))
        tk.Entry(root, textvariable=self.output_name, width=40).pack(fill="x", padx=10)

        tk.Button(root, text="Genera PDF", command=self.generate_pdf, bg="#3c9", fg="white").pack(pady=10)

        tk.Label(root, text="Log:").pack(anchor="w", padx=10)
        self.log_box = scrolledtext.ScrolledText(root, height=12, state="disabled")
        self.log_box.pack(fill="both", expand=True, padx=10, pady=(0,10))

    def log(self, text):
        self.log_box.configure(state="normal")
        self.log_box.insert(tk.END, text + "\n")
        self.log_box.configure(state="disabled")
        self.log_box.see(tk.END)
        self.root.update_idletasks()

    def choose_folder(self):
        folder = filedialog.askdirectory(title="Seleziona la cartella Markdown")
        if folder:
            self.folder_path.set(folder)

    def generate_pdf(self):
        folder = self.folder_path.get().strip()
        output_name = self.output_name.get().strip()

        if not folder:
            messagebox.showwarning("Attenzione", "Seleziona una cartella contenente i file Markdown.")
            return

        if not output_name.endswith(".pdf"):
            output_name += ".pdf"

        folder_path = Path(folder)
        output_path = folder_path / output_name

        # Trova i file Markdown numerati
        md_files = sorted(folder_path.glob("[0-9][0-9]_*.md"))
        if not md_files:
            messagebox.showerror("Errore", "Nessun file Markdown numerato trovato nella cartella.")
            return

        self.log(f"Trovati {len(md_files)} file Markdown:")
        for f in md_files:
            self.log(f"  - {f.name}")

        combined_md = folder_path / "_manuale_unico_temp.md"
        self.log(f"\nUnione dei file in {combined_md.name}...")

        try:
            with open(combined_md, "w", encoding="utf-8") as out:
                for f in md_files:
                    out.write(f"\n\n# --- {f.name} ---\n\n")
                    out.write(f.read_text(encoding="utf-8"))
                    out.write("\n\n")
            self.log("File unito con successo.")
        except Exception as e:
            messagebox.showerror("Errore durante unione", str(e))
            return

        # Comando Pandoc
        cmd = [
            "pandoc", str(combined_md),
            "-o", str(output_path),
            "--toc",
            "--pdf-engine=xelatex",
            #--pdf-engine=wkhtmltopdf",
            "-V", "mainfont=DejaVu Serif",
            "-V", "geometry:margin=2.5cm"
        ]

        self.log("\nEsecuzione Pandoc...")
        try:
            result = subprocess.run(cmd, capture_output=True, text=True)
            if result.returncode == 0:
                self.log("✅ PDF generato correttamente:")
                self.log(f"→ {output_path}")
                messagebox.showinfo("Completato", f"PDF generato: {output_path}")
            else:
                self.log("❌ Errore Pandoc:")
                self.log(result.stderr)
                messagebox.showerror("Errore Pandoc", result.stderr)
        except FileNotFoundError:
            messagebox.showerror("Pandoc non trovato",
                                 "Pandoc non è installato o non è nel PATH di sistema.\n"
                                 "Scaricalo da https://pandoc.org/installing.html")
        finally:
            if combined_md.exists():
                combined_md.unlink()  # Rimuove il file temporaneo

if __name__ == "__main__":
    root = tk.Tk()
    app = MarkdownToPDFApp(root)
    root.mainloop()



