from PIL import Image, ImageDraw

def update_favicon_v4():
    logo_path = "/Users/apple/.gemini/antigravity-ide/brain/822556bd-47a7-4c07-8975-803618af0a3a/media__1781946188768.png"
    
    # 1. Load original logo
    logo_img = Image.open(logo_path).convert("RGBA")
    
    # 2. Crop the circle icon: X: 85 to 149 (width=65), Y: 44 to 83 (height=40)
    icon_w = 65
    icon_h = 40
    icon_crop = logo_img.crop((85, 44, 150, 84))
    
    # 3. Strip any white background from the cropped icon
    icon_tp = Image.new("RGBA", (icon_w, icon_h))
    pixels_ic = icon_crop.load()
    pixels_tp = icon_tp.load()
    for x in range(icon_w):
        for y in range(icon_h):
            r, g, b, a = pixels_ic[x, y]
            if r >= 248 and g >= 248 and b >= 248:
                pixels_tp[x, y] = (0, 0, 0, 0)
            else:
                pixels_tp[x, y] = (r, g, b, a)
                
    # 4. Place it inside a square 65x65 box to prevent squishing
    square_size = 65
    square_icon = Image.new("RGBA", (square_size, square_size), (0, 0, 0, 0))
    y_offset = (square_size - icon_h) // 2
    square_icon.paste(icon_tp, (0, y_offset), icon_tp)
    
    # 5. Draw a solid white circle background behind the square icon
    favicon_img = Image.new("RGBA", (square_size, square_size), (0, 0, 0, 0))
    draw = ImageDraw.Draw(favicon_img)
    
    # Draw solid white circle (leave a small transparent margin around it for clean rendering)
    margin = 2
    draw.ellipse(
        [margin, margin, square_size - margin, square_size - margin],
        fill=(255, 255, 255, 255)
    )
    
    # Paste the purple logo on top of the white circle
    favicon_img.paste(square_icon, (0, 0), square_icon)
    
    # 6. Resize to standard sizes and save
    favicon_32 = favicon_img.resize((32, 32), Image.Resampling.LANCZOS)
    favicon_48 = favicon_img.resize((48, 48), Image.Resampling.LANCZOS)
    
    # Save favicon.ico to public/ and src/app/
    favicon_32.save("public/favicon.ico", format="ICO", sizes=[(32, 32), (48, 48)])
    favicon_32.save("src/app/favicon.ico", format="ICO", sizes=[(32, 32), (48, 48)])
    
    # Save PNG versions
    favicon_48.save("public/favicon.png", "PNG")
    favicon_48.save("public/apple-icon.png", "PNG")
    
    print("Successfully generated non-squished favicon with solid white circle background!")

if __name__ == "__main__":
    update_favicon_v4()
