from rembg import remove
from PIL import Image
import numpy as np

def is_white_background(image_array, threshold_white=200, threshold_dark=50):
    img_corners = [
        image_array[0, 0],  # top-left corner
        image_array[0, -1], # top-right corner
        image_array[-1, 0], # bottom-left corner
        image_array[-1, -1] # bottom-right corner,
    ]
    
    height, width = image_array.shape[:2]

    englobed_corners = [
        image_array[25, 25],                          # Top-left (inward)
        image_array[25, width - 26],                  # Top-right (inward)
        image_array[height - 26, 25],                 # Bottom-left (inward)
        image_array[height - 26, width - 26]          # Bottom-right (inward)
    ]
  
    dark_found = False
    white_found = False

    for corner in img_corners:
        r, g, b, _ = corner
        
        if r >= threshold_white and g >= threshold_white and b >= threshold_white:
            white_found = True
    
    for corner in englobed_corners:
        r, g, b, _ = corner
        
        if r <= threshold_dark and g <= threshold_dark and b <= threshold_dark:
            dark_found = True
    
    
    

    return dark_found and white_found

# ------------------------------------------------------------------------------------

def remove_bckgrd(input_path, output_path):
    
    input_image = Image.open(input_path)

    coverted = input_image.convert("RGBA")
    image_array = np.array(coverted)

    if is_white_background(image_array):
        
        output_image = remove(input_image)
        output_image = output_image.convert("RGBA")
        bbox = output_image.getbbox()
        cropped_image = output_image.crop(bbox)
    else:    
        output_image_1 = remove(input_image)
        output_image_1 = output_image_1.convert("RGBA")

        output_image_2 = remove(output_image_1)
        output_image_2 = output_image_2.convert("RGBA")
        bbox_2 = output_image_2.getbbox()

        cropped_image = output_image_1.crop(bbox_2)

    cropped_image.save(output_path)

remove_bckgrd('../python/image.jpg', '../public/cropped_img.png')
