import tkinter as tk
from tkinter import filedialog, messagebox
import re

def scale_rgb(value):
    return round(float(value) * 2.55, 4)

def process_ti1_file(input_path, output_path):
    with open(input_path, 'r') as f:
        lines = f.readlines()

    header = []
    data_lines = []
    in_data = False
    patch_count = 0

    for line in lines:
        if line.strip().startswith("NUMBER_OF_SETS"):
            patch_count = int(line.strip().split()[-1])
        if line.strip() == "BEGIN_DATA":
            in_data = True
            continue
        if line.strip() == "END_DATA":
            in_data = False
            break
        if in_data:
            parts = line.strip().split()
            if len(parts) >= 6:
                # Scale RGB values
                scaled_rgb = [str(scale_rgb(v)) for v in parts[1:4]]
                data_lines.append(f"{parts[0]} {' '.join(scaled_rgb)} {' '.join(parts[4:7])}")
        else:
            header.append(line)

    # Modify COLOR_REP and TOTAL_INK_LIMIT if needed
    header = [re.sub(r'COLOR_REP\s+".*"', 'COLOR_REP "RGB"', h) for h in header]
    header = [re.sub(r'TOTAL_INK_LIMIT\s+".*"', '', h) for h in header]

    with open(output_path, 'w') as f:
        for line in header:
            f.write(line)
        f.write("NUMBER_OF_SETS {}\n".format(len(data_lines)))
        f.write("BEGIN_DATA\n")
        for line in data_lines:
            f.write(line + "\n")
        f.write("END_DATA\n")

def select_file():
    input_path = filedialog.askopenfilename(filetypes=[("TI1 files", "*.ti1"), ("All files", "*.*")])
    if not input_path:
        return
    output_path = filedialog.asksaveasfilename(defaultextension=".cgats", filetypes=[("CGATS files", "*.cgats")])
    if not output_path:
        return
    try:
        process_ti1_file(input_path, output_path)
        messagebox.showinfo("Success", f"Cleaned CGATS file saved to:\n{output_path}")
    except Exception as e:
        messagebox.showerror("Error", str(e))

# GUI setup
root = tk.Tk()
root.title("ArgyllCMS to ColorPort CGATS Cleaner")
root.geometry("400x150")

label = tk.Label(root, text="Convert ArgyllCMS .ti1 to ColorPort-compatible CGATS")
label.pack(pady=20)

btn = tk.Button(root, text="Select and Convert File", command=select_file)
btn.pack(pady=10)

root.mainloop()