import tkinter as tk
from tkinter import filedialog, messagebox
from reportlab.pdfgen import canvas
from reportlab.lib.pagesizes import A4
from reportlab.lib import colors
import os
import unicodedata
from textwrap import wrap

def remove_diacritics(text):
    """Elimină diacriticele din text"""
    normalized = unicodedata.normalize('NFKD', text)
    return ''.join(c for c in normalized if not unicodedata.combining(c))

def create_pdf(input_files, header_text, footer_text):
    for txt_file in input_files:
        pdf_file = os.path.splitext(txt_file)[0] + ".pdf"
        c = canvas.Canvas(pdf_file, pagesize=A4)
        width, height = A4
        
        # Margini și setări
        left_margin = 50
        right_margin = 50
        top_margin = 50
        bottom_margin = 50
        usable_width = width - left_margin - right_margin
        usable_height = height - top_margin - bottom_margin
        
        # Fonturi
        c.setFont("Helvetica", 12)
        line_height = 14
        
        def add_page_elements(page_num, total_pages):
            # Header
            c.setFillColor(colors.red)
            c.drawString(left_margin, height - 30, header_clean.upper())
            c.line(left_margin, height - 40, width - right_margin, height - 40)
            # Footer
            c.drawString(left_margin, 30, footer_clean.upper())
            c.line(left_margin, 40, width - right_margin, 40)
            # Număr pagină
            c.setFont("Helvetica", 8)
            page_text = f"Pagina {page_num} din {total_pages}"
            text_width = c.stringWidth(page_text, "Helvetica", 8)
            c.drawString((width - text_width) / 2, 20, page_text)
            c.setFont("Helvetica", 12)
            c.setFillColor(colors.black)
            return height - top_margin - 20
        
        # Curățare text header/footer
        header_clean = remove_diacritics(header_text)
        footer_clean = remove_diacritics(footer_text)
        
        # Citire text și calcul preliminar al numărului de pagini
        with open(txt_file, 'r', encoding='utf-8') as f:
            text = f.read()
            text_clean = remove_diacritics(text)
            
            # Calcul aproximativ al liniilor
            char_width = c.stringWidth("M", "Helvetica", 12)
            max_chars = int(usable_width / char_width) - 5
            lines = []
            paragraphs = text_clean.split('\n\n')
            for paragraph in paragraphs:
                if paragraph.strip():
                    lines.extend(wrap(paragraph.strip(), width=max_chars))
                    lines.append("")  # spațiu între paragrafe
            total_lines = len(lines)
            lines_per_page = int(usable_height / line_height)
            total_pages = (total_lines + lines_per_page - 1) // lines_per_page or 1
        
        # Generare PDF
        page_num = 1
        y = add_page_elements(page_num, total_pages)
        
        for paragraph in paragraphs:
            if not paragraph.strip():
                continue
                
            # Formatare paragraf
            char_width = c.stringWidth("M", "Helvetica", 12)
            max_chars = int(usable_width / char_width) - 5
            lines = wrap(paragraph.strip(), width=max_chars)
            first_line = True
            
            for line in lines:
                if y < bottom_margin + 40:
                    c.showPage()
                    page_num += 1
                    y = add_page_elements(page_num, total_pages)
                
                x_start = left_margin + (20 if first_line else 0)
                c.drawString(x_start, y, line.strip())
                y -= line_height
                first_line = False
            
            y -= line_height / 2
        
        c.save()

def main():
    root = tk.Tk()
    root.withdraw()
    
    # Dialog pentru header
    header = tk.simpledialog.askstring("Header", "Introdu textul pentru header (ex: SECRET, TOP SECRET):",
                                     parent=root)
    if not header:
        header = "CONFIDENTIAL"
    
    # Dialog pentru footer
    footer = tk.simpledialog.askstring("Footer", "Introdu textul pentru footer:",
                                     parent=root)
    if not footer:
        footer = "COMPANY USE ONLY"
    
    # Selectare fișiere
    files = filedialog.askopenfilenames(
        title="Selectează fișierele text",
        filetypes=[("Text files", "*.txt")]
    )
    
    if files:
        try:
            create_pdf(files, header, footer)
            messagebox.showinfo("Succes", "Fișierele au fost convertite în PDF cu succes!")
        except Exception as e:
            messagebox.showerror("Eroare", f"A apărut o eroare: {str(e)}")
    
    root.destroy()

if __name__ == "__main__":
    main()
