import re
import replicate
import tkinter as tk


def parse_hex_values(input_string):
    # Capitalize the entire input string
    capitalized_string = input_string.upper()

    # Use regex to find all hex color values in the string
    hex_values = re.findall(r'#[0-9A-F]{6}', capitalized_string)

    return hex_values


def hex_to_rgb(hex_values):
    rgb_values = []
    for hex_value in hex_values:
        hex_value = hex_value.lstrip('#')
        rgb = [int(hex_value[i:i+2], 16) for i in (0, 2, 4)]
        rgb_values.append(rgb)
    return rgb_values


def noun_rgb_hex_llama_3_70b(noun: str) -> list[list[int]]:
    response = ""
    # The meta/meta-llama-3-8b model can stream output as it's running.
    for event in replicate.stream(
            "meta/meta-llama-3-70b-instruct",
            input={
                "top_k": 0,
                "top_p": 0.95,
                "prompt": f"give me a color pallet for a {noun} svg. Don't worry about details. format should be a list of uppercase hex ie #000000 #FFFFFF. don't explain your output",
                "max_tokens": 512,
                "temperature": 0.7,
                "system_prompt": "You are a helpful assistant",
                "length_penalty": 1,
                "max_new_tokens": 512,
                "stop_sequences": "<|end_of_text|>,<|eot_id|>",
                "prompt_template": "<|begin_of_text|><|start_header_id|>system<|end_header_id|>\n\n{system_prompt}<|eot_id|><|start_header_id|>user<|end_header_id|>\n\n{prompt}<|eot_id|><|start_header_id|>assistant<|end_header_id|>\n\n",
                "presence_penalty": 0,
                "log_performance_metrics": False
            },
    ):
        response += str(event)

    hex_values = parse_hex_values(response)
    rgb_values = hex_to_rgb(hex_values)
    return rgb_values

def rgb_to_hex(rgb):
    """Convert an RGB tuple to a HEX color string."""
    return f"#{rgb[0]:02x}{rgb[1]:02x}{rgb[2]:02x}"

def show_palette(rgb_colors):
    """Display the given RGB colors as a palette."""
    # Clear the frame
    for widget in frame.winfo_children():
        widget.destroy()

    # Convert RGB colors to HEX and display them
    hex_colors = [rgb_to_hex(color) for color in rgb_colors]
    for hex_color in hex_colors:
        swatch = tk.Frame(frame, bg=hex_color, width=100, height=50)
        swatch.pack(side=tk.LEFT, padx=5)

    # Update the label to show the HEX codes
    color_label.config(text=" ".join(hex_colors))

def create_app(rgb_colors):
    """Create and run the Tkinter app to display the palette."""
    global frame, color_label

    app = tk.Tk()
    app.title("RGB Color Palette Viewer")

    frame = tk.Frame(app)
    frame.pack(pady=20)

    color_label = tk.Label(app, text="", font=("Helvetica", 12))
    color_label.pack(pady=10)

    # Show the provided palette on start
    show_palette(rgb_colors)

    app.mainloop()

if __name__ == "__main__":
    # Example usage
    #input_string = "#f9c22e #d89c34 #a67c33 #5a3a1a #3e2a16"
    #hex_values = parse_hex_values(input_string)
    #print(hex_values)
    #rgb_values = hex_to_rgb(hex_values)
    #print(rgb_values)
    colors = noun_rgb_hex_llama_3_70b("lion")
    create_app(colors)

