import tkinter as tk
from tkinter import filedialog, messagebox, ttk
import fitz  # PyMuPDF
import os

class PdfCropperApp:
    def __init__(self, root):
        self.root = root
        self.root.title("מחלץ שער הציון - גרסה 1.2")
        self.root.geometry("500x250")
        self.root.resizable(False, False)
        
        self.root.tk.call('tk', 'windowingsystem')
        
        self.input_path = tk.StringVar()
        
        main_frame = tk.Frame(root, padx=20, pady=20)
        main_frame.pack(expand=True, fill="both")

        tk.Label(main_frame, text="בחר קובץ PDF (משנה ברורה):", font=("Arial", 12)).pack(pady=5)
        
        file_frame = tk.Frame(main_frame)
        file_frame.pack(fill="x", pady=5)
        
        self.entry = tk.Entry(file_frame, textvariable=self.input_path, width=40)
        self.entry.pack(side="right", padx=5)
        
        btn_browse = tk.Button(file_frame, text="עיון...", command=self.browse_file)
        btn_browse.pack(side="right")

        self.btn_start = tk.Button(main_frame, text="התחל המרה", command=self.process_pdf, 
                                   bg="#4CAF50", fg="white", font=("Arial", 11, "bold"), height=2)
        self.btn_start.pack(fill="x", pady=20)

        self.progress = ttk.Progressbar(main_frame, orient="horizontal", length=100, mode="determinate")
        self.progress.pack(fill="x")

    def browse_file(self):
        filename = filedialog.askopenfilename(filetypes=[("PDF Files", "*.pdf")])
        if filename:
            self.input_path.set(filename)

    def show_missing_pages_window(self, missing_pages):
        top = tk.Toplevel(self.root)
        top.title("עמודים ללא שער הציון")
        top.geometry("350x400")
        
        label = tk.Label(top, text="העמודים הבאים לא הכילו את 'שער הציון':", font=("Arial", 10, "bold"), pady=10)
        label.pack()

        text_area = tk.Text(top, wrap="word", font=("Arial", 10), padx=10, pady=10)
        text_area.pack(expand=True, fill="both", padx=10, pady=5)
        
        pages_str = ", ".join(map(str, missing_pages))
        text_area.insert(tk.END, pages_str)
        text_area.config(state="disabled")

        btn_close = tk.Button(top, text="סגור", command=top.destroy, width=10)
        btn_close.pack(pady=10)

    def process_pdf(self):
        input_file = self.input_path.get()
        if not input_file:
            messagebox.showwarning("שגיאה", "אנא בחר קובץ תחילה")
            return

        output_file = os.path.splitext(input_file)[0] + "_שער_הציון_בלבד.pdf"
        
        try:
            doc = fitz.open(input_file)
            out_doc = fitz.open()
            
            total_pages = len(doc)
            self.progress["maximum"] = total_pages
            
            pages_found = 0
            missing_pages = []
            
            # רשימת וריאציות לזיהוי OCR משובש
            search_variations = [
                "שער הציון", "שער הציון:", "שער הציין", 
                "שער", "שעד", "ש*,)ר",  
                "שער הצין", "שער הציוז", "שער דציון", 
                "שעד הציון", "שערהציון", "שער הציון."
            ]
            
            for i in range(total_pages):
                page = doc[i]
                text_instances = []
                
                # הגדרת אזור חיפוש המוגבל לשליש התחתון של העמוד בלבד
                search_area = fitz.Rect(0, page.rect.height * 2 / 3, page.rect.width, page.rect.height)
                
                # בדיקת כל הווריאציות באזור השליש התחתון עד למציאת אחת שמתאימה
                for var in search_variations:
                    text_instances = page.search_for(var, clip=search_area)
                    if text_instances:
                        break
                
                if text_instances:
                    y_start = text_instances[0].y0 - 5
                    page_rect = page.rect
                    crop_rect = fitz.Rect(0, y_start, page_rect.width, page_rect.height)
                    
                    new_page = out_doc.new_page(width=page_rect.width, 
                                               height=page_rect.height - y_start)
                    
                    new_page.show_pdf_page(new_page.rect, doc, i, clip=crop_rect)
                    pages_found += 1
                else:
                    missing_pages.append(i + 1)
                
                self.progress["value"] = i + 1
                self.root.update_idletasks()

            if pages_found > 0:
                out_doc.save(output_file)
                messagebox.showinfo("הצלחה", f"הסיום בהצלחה!\nנוצר קובץ חדש עם {pages_found} עמודים.")
                
                if missing_pages:
                    self.show_missing_pages_window(missing_pages)
            else:
                messagebox.showwarning("לא נמצא תוכן", "לא נמצאו עמודים המכילים את הכותרת 'שער הציון' בשליש התחתון")
            
            out_doc.close()
            doc.close()
            
        except Exception as e:
            messagebox.showerror("שגיאה", f"אירעה שגיאה בתהליך:\n{str(e)}")
        
        finally:
            self.progress["value"] = 0

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