import fitz
from PIL import Image
import numpy as np

doc = fitz.open(r'C:\Users\Roel\clawd\sneakerpicks\public\sneakerpicks-logo.pdf')
page = doc[0]
w, h = page.rect.width, page.rect.height
hw, hh = w/2, h/2

variants = {
    'light': fitz.Rect(0, 0, hw, hh),      # dark text on cream bg
    'dark': fitz.Rect(hw, 0, w, hh),        # light text on dark bg
}

for name, rect in variants.items():
    scale = 2000 / rect.width
    mat = fitz.Matrix(scale, scale)
    pix = page.get_pixmap(matrix=mat, clip=rect, alpha=False)
    
    # Convert to PIL Image
    img = Image.frombytes("RGB", [pix.width, pix.height], pix.samples)
    img_np = np.array(img)
    
    # Get the background color from corner pixel
    bg_color = img_np[5, 5]
    print(f"{name}: bg color = {bg_color}")
    
    # Create alpha mask: pixels similar to bg become transparent
    diff = np.abs(img_np.astype(int) - bg_color.astype(int))
    max_diff = np.max(diff, axis=2)
    
    # Threshold: if pixel is very close to bg, make transparent
    alpha = np.where(max_diff < 30, 0, 255).astype(np.uint8)
    
    # Create RGBA image
    rgba = Image.fromarray(np.dstack([img_np, alpha]))
    
    # Crop to content (non-transparent area)
    bbox = rgba.getbbox()
    if bbox:
        rgba = rgba.crop(bbox)
    
    out_path = f'C:\\Users\\Roel\\clawd\\sneakerpicks\\public\\logo-{name}-transparent.png'
    rgba.save(out_path)
    print(f"{name}: saved {rgba.width}x{rgba.height} -> {out_path}")

print("Done!")
