import tkinter as tk
from tkinter import filedialog, messagebox
from tkinter.scrolledtext import ScrolledText
from PIL import Image
import anthropic
import os
import base64
from io import BytesIO
import json
import re

# Initialize the Anthropic client
client = anthropic.Anthropic()

# Define the maximum width and height for resizing
#MAX_WIDTH = 800
#MAX_HEIGHT = 800

# Function to process the selected images and display JSON output
def process_images():
    # Check if any images are selected
    if not image_paths:
        messagebox.showerror("Error", "No images selected. Please add images.")
        return
    
    # Initialize the content list with the initial text message
    content_list = [
        {
            "type": "text",
            "text": "Трябва ми информация в табличен вид за всяка партия колко гласа има от хартиената бюлетина и от гласуване с машина, също коя секция е и кой протокол. Също така освен цифром между партията и цифром гласове са изписани словом гласове. Използвай словом за да сравниш дали коректно си разчел цифрата моля. Също така имай предвид че регистрираните партии за тези избори са следните с оглед вярното им разчитане:            2. ПП ГЛАС НАРОДЕН, 3. Социалистическа партия Български път, 4. ПП ВЕЛИЧИЕ, 5. Булгари, 6. МОЯ СТРАНА БЪЛГАРИЯ, 7. ПП ИМА ТАКЪВ НАРОД, 8. ДПС-Ново начало, 9. БРИГАДА, 10. Партия на ЗЕЛЕНИТЕ, 11. ПРАВОТО, 12. ВЪЗРАЖДАНЕ, 13. АЛИАНС ЗА ПРАВА И СВОБОДИ – АПС, 14. БЪЛГАРСКИ НАЦИОНАЛЕН СЪЮЗ – НД, 15. БСДД – ДИРЕКТНА ДЕМОКРАЦИЯ, 16. СИНЯ БЪЛГАРИЯ, 17. ПП МЕЧ, 18. ГЕРБ-СДС, 19. АТАКА, 20. ПП НАРОДНА ПАРТИЯ ИСТИНАТА И САМО ИСТИНАТА, 21. ПРЯКА ДЕМОКРАЦИЯ, 22. КП СВОБОДНИ ИЗБИРАТЕЛИ (РБ, ССД и ЗС), 23. БТР – БЪЛГАРИЯ НА ТРУДА И РАЗУМА, 24. КОЙ, 25. КП РУСОФИЛИ ЗА БЪЛГАРИЯ, 26. КОАЛИЦИЯ ПРОДЪЛЖАВАМЕ ПРОМЯНАТА – ДЕМОКРАТИЧНА БЪЛГАРИЯ, 27. БЪЛГАРСКИ ВЪЗХОД, 28. БСП – ОБЕДИНЕНА ЛЕВИЦА"
        }
    ]
    
    # Process each selected image file
    for image_path in image_paths:
        with Image.open(image_path) as img:
            # Convert RGBA images to RGB to ensure compatibility with JPEG
            if img.mode == "RGBA":
                img = img.convert("RGB")
            
            # Resize image if it's larger than the maximum dimensions
            #img.thumbnail((MAX_WIDTH, MAX_HEIGHT))
            
            # Save resized image to a buffer
            buffer = BytesIO()
            img.save(buffer, format="JPEG")
            # Encode the buffer image to base64
            encoded_image = base64.b64encode(buffer.getvalue()).decode("utf-8")
            
            # Append the encoded image to the content list
            content_list.append({
                "type": "image",
                "source": {
                    "type": "base64",
                    "media_type": "image/jpeg",
                    "data": encoded_image
                }
            })

    # Send the message to Anthropic's API
    client = anthropic.Client(api_key='sk-bnz-api68-XXXXXXXXXXXXXXXXXXXXXXXXXXXsssssssssssssssAAAAAAAAAAAAAAA')
    message = client.messages.create(
        model="claude-3-5-sonnet-20241022",
        max_tokens=8000,
        temperature=0,
        messages=[
            {
                "role": "user",
                "content": content_list
            }
        ]
    )

    # Extract and format the response content into JSON
    output_text = message.content[0].text  # Get the text content of the first response block
    rows = output_text.splitlines()  # Split the text by lines

    # Filter and structure the table rows
    table_data = []
    for row in rows:
        # Match table rows with parties and votes (ignore header rows)
        match = re.match(r"\| (.+?) \| (\d+) \| (\d+) \| (\d+) \|", row)
        if match:
            # Extract data as dictionary entries for JSON structure
            table_data.append({
                "party": match.group(1).strip(),
                "paper_votes": int(match.group(2)),
                "machine_votes": int(match.group(3)),
                "total": int(match.group(4))
            })

    # Convert the structured data to JSON format
    json_output = json.dumps(table_data, indent=2, ensure_ascii=False)

    # Display the JSON output in the text area
    output_text_area.delete(1.0, tk.END)
    output_text_area.insert(tk.END, json_output)

# Function to select images
def select_images():
    global image_paths
    image_paths = filedialog.askopenfilenames(filetypes=[("Image files", "*.jpg *.jpeg *.png")])
    if image_paths:
        selected_files_label.config(text=f"Selected {len(image_paths)} images")

# Create the main window
root = tk.Tk()
root.title("Election Image Processor")
root.geometry("600x500")

# GUI Components
select_button = tk.Button(root, text="Select Images", command=select_images)
select_button.pack(pady=10)

selected_files_label = tk.Label(root, text="No images selected")
selected_files_label.pack()

process_button = tk.Button(root, text="Process", command=process_images)
process_button.pack(pady=10)

output_label = tk.Label(root, text="JSON Output:")
output_label.pack()

output_text_area = ScrolledText(root, width=70, height=20)
output_text_area.pack(pady=10)

# Run the application
root.mainloop()
