import cv2
import numpy as np
import os
import csv

DECAY_FILTER = 101  

color_scores = {
    'red': 6,
    'orange': 5,
    'yellow': 4,
    'green': 3,
    'blue': 2,
    'purple': 1,
    'other': 0
}

def get_color_score(bgr):
    blue, green, red = bgr

    if red > 200 and green < 100 and blue < 100:
        return color_scores['red']
    elif red > 200 and green > 100 and green < 200 and blue < 100:
        return color_scores['orange']
    elif red > 200 and green > 200 and blue < 100:
        return color_scores['yellow']
    elif green > 150 and red < 50 and blue < 150:
        return color_scores['green']
    elif blue > 200 and red < 50 and green < 150:
        return color_scores['blue']
    elif red > 100 and blue > 100 and green < 150:
        return color_scores['purple']
    else:
        return color_scores['other']

image_files = [f for f in os.listdir() if f.endswith('******.jpg') or f.endswith('******.jpg')]
first_img = cv2.imread(image_files[0])
height, width, channels = first_img.shape

score_sum = np.zeros((height, width), dtype=np.float32)

for image_file in image_files:
    img = cv2.imread(image_file)
    for y in range(height):
        for x in range(width):
            score_sum[y, x] += get_color_score(img[y, x])

average_score = score_sum / len(image_files)

def score_to_color(score):
    if score >= 5:
        return (0, 75, 255)  
    elif score >= 4:
        return (0, 170, 246)  
    elif score >= 3:
        return (0, 231, 242)  
    elif score >= 2:
        return (107, 176, 0) 
    elif score >= 1:
        return (255, 113, 25)  
    elif score >= 0.1:
        return (153, 0, 153)  
    else:
        return (0, 0, 0)  

colorized_image = np.zeros((height, width, 3), dtype=np.uint8)
for y in range(height):
    for x in range(width):
        colorized_image[y, x] = score_to_color(average_score[y, x])

output_folder = 'Jpegs'
os.makedirs(output_folder, exist_ok=True)

selection_start = None
selection_end = None
is_selecting = False

def mouse_callback(event, x, y, flags, param):
    global selection_start, selection_end, is_selecting
    if event == cv2.EVENT_LBUTTONDOWN:  
        selection_start = (x, y)
        is_selecting = True
    elif event == cv2.EVENT_MOUSEMOVE and is_selecting:  
        selection_end = (x, y)
    elif event == cv2.EVENT_LBUTTONUP:  
        selection_end = (x, y)
        is_selecting = False
        apply_blur() 

def apply_blur():
    global selection_start, selection_end, colorized_image
    if selection_start and selection_end:
        x1, y1 = selection_start
        x2, y2 = selection_end
        x1, x2 = min(x1, x2), max(x1, x2)
        y1, y2 = min(y1, y2), max(y1, y2)

        original_file_path = os.path.join(output_folder, 'GFP.jpg')
        cv2.imwrite(original_file_path, colorized_image)
        print(f"The image before blurring has been saved to ‘{original_file_path}’.")

        blurred_image = colorized_image.copy()
        blurred_section = cv2.GaussianBlur(colorized_image[y1:y2, x1:x2], (DECAY_FILTER, DECAY_FILTER), 0)
        blurred_image[y1:y2, x1:x2] = blurred_section

        cv2.imshow('Preview: Blurred Image', blurred_image)
        cv2.waitKey(1)  

        while True:
            user_input = input("Do you want to save the file (y/n)? ").strip().lower()
            if user_input == 'y':
                blurred_file_path = os.path.join(output_folder, 'blurred_selected_area.jpg')
                cv2.imwrite(blurred_file_path, blurred_image)
                print(f"The image before blurring has been saved to ‘{original_file_path}’.")
                cv2.destroyAllWindows()
                exit() 
            elif user_input == 'n':
                print("Return to selection without saving.")
                cv2.destroyWindow('Preview: Blurred Image')
                break
            else:
                print("Invalid input. Please enter ‘y’ or ‘n’.")

cv2.namedWindow('Colorized Image')
cv2.setMouseCallback('Colorized Image', mouse_callback)

while True:
    display_image = colorized_image.copy()
    if selection_start and selection_end:
        cv2.rectangle(display_image, selection_start, selection_end, (0, 255, 0), 2)

    cv2.imshow('Colorized Image', display_image)
    key = cv2.waitKey(1) & 0xFF
    if key == 27:  
        break

cv2.destroyAllWindows()
