import os
from PIL import Image
import numpy as np

def process_logo():
    if not os.path.exists('logo.webp'):
        print("logo.webp not found")
        return

    img = Image.open('logo.webp').convert('RGB')
    arr = np.array(img, dtype=float)

    # Detect background level
    bg_color = np.percentile(arr, 95, axis=(0,1))
    diff = np.linalg.norm(arr - bg_color, axis=2)

    # Crop coordinates
    mask = diff > 8
    coords = np.argwhere(mask)
    if len(coords) == 0:
        print("No logo content detected")
        return

    min_y, min_x = coords.min(axis=0)
    max_y, max_x = coords.max(axis=0)

    # Add padding
    padding = 24
    min_y = max(0, min_y - padding)
    max_y = min(arr.shape[0]-1, max_y + padding)
    min_x = max(0, min_x - padding)
    max_x = min(arr.shape[1]-1, max_x + padding)

    cropped_diff = diff[min_y:max_y+1, min_x:max_x+1]
    h, w = cropped_diff.shape

    # Calculate smooth contrast-enhanced alpha
    max_diff = cropped_diff.max()
    alpha = np.clip((cropped_diff - 4.0) / (max_diff - 4.0) * 255.0, 0, 255)
    alpha = np.power(alpha / 255.0, 0.65) * 255.0

    # 1. Dark Slate (#0F172A) version for pure white/light navbar backgrounds
    dark_slate_rgb = np.array([15, 23, 42], dtype=float)
    rgba_dark = np.zeros((h, w, 4), dtype=np.uint8)
    rgba_dark[:, :, :3] = dark_slate_rgb
    rgba_dark[:, :, 3] = alpha.astype(np.uint8)
    img_dark = Image.fromarray(rgba_dark, 'RGBA')
    img_dark.save('static/logo.webp')
    img_dark.save('public/logo.webp')
    img_dark.save('static/logo-dark.webp')

    # 2. Light White (#FFFFFF) version for dark footer backgrounds
    rgba_light = np.zeros((h, w, 4), dtype=np.uint8)
    rgba_light[:, :, :3] = 255
    rgba_light[:, :, 3] = alpha.astype(np.uint8)
    img_light = Image.fromarray(rgba_light, 'RGBA')
    img_light.save('static/logo-light.webp')
    img_light.save('public/logo-light.webp')

    print(f"Processed logo: size {w}x{h}, transparent background, crisp slate dark & light variants saved!")

if __name__ == '__main__':
    process_logo()
