from PIL import Image
import numpy as np
import cv2

# Step 1: Read the file
with open('cmy.txt', 'r') as file:
    content = file.read().strip()

# Step 2: Split the content by comma
fc, fm, fy, filename = content.split(',')

# Step 3: Convert CMY values to integers (assuming input values are in the 0-100 range)
fc = int(fc)
fm = int(fm)
fy = int(fy)

# Now you have the variables
print(f"Cyan: {fc}, Magenta: {fm}, Yellow: {fy}, Filename: {filename}")


def create_lut(curve_points):
    lut = np.arange(256, dtype=np.uint8)
    x = list(curve_points.keys())
    y = list(curve_points.values())

    for i in range(256):
        lut[i] = np.interp(i, x, y)

    return lut


def apply_curves_cmyk(image, curve_c, curve_m, curve_y):
    # Split image into channels (assuming CMYK is in the order C, M, Y, K)
    c, m, y, k = cv2.split(image)

    # Create LUTs
    lut_c = create_lut(curve_c)
    lut_m = create_lut(curve_m)
    lut_y = create_lut(curve_y)

    # Apply LUTs to CMY channels
    c = cv2.LUT(c, lut_c)
    m = cv2.LUT(m, lut_m)
    y = cv2.LUT(y, lut_y)

    # Merge channels back, keeping K channel unchanged
    return cv2.merge((c, m, y, k))


# Convert input values from 0-100 range to 0-255 range
fc_scaled = int((fc / 100) * 255)
fm_scaled = int((fm / 100) * 255)
fy_scaled = int((fy / 100) * 255)

# Define curve points for CMY channels using scaled values
curve_c = {0: 0, 127: fc_scaled, 255: 255}
curve_m = {0: 0, 102: fm_scaled, 255: 255}
curve_y = {0: 0, 102: fy_scaled, 255: 255}

# Read input CMYK image using Pillow
image_pil = Image.open(filename)
if image_pil.mode == 'CMYK':
    # Convert the image to a NumPy array
    img = np.array(image_pil)

    # Apply curve adjustments
    adjusted_img = apply_curves_cmyk(img, curve_c, curve_m, curve_y)

    # Convert back to an image and save the output
    adjusted_img_pil = Image.fromarray(adjusted_img, mode='CMYK')
    adjusted_img_pil.save('fix-' + filename)
else:
    print("The image is not in CMYK format.")
