from rembg import remove
from PIL import Image
import os

input_path = 'images/AL - HAJ abdul  hakim saifi chairman : founder.jpeg'
bg_path = '/Users/mac/.gemini/antigravity/brain/0ef1752a-4b85-4c35-8da1-86fd8af1a6bd/office_background_1777980218538.png'
output_path = 'images/chairman_new.jpg'

print("Opening images...")
# Open the original image
input_image = Image.open(input_path).convert("RGBA")

# Remove background
print("Removing background...")
subject_image = remove(input_image)

# Open background image
bg_image = Image.open(bg_path).convert("RGBA")

# Resize subject to fit background reasonably (e.g., placing him behind/above the desk)
# Background is 1024x1024 typically from generate_image
bg_w, bg_h = bg_image.size
subj_w, subj_h = subject_image.size

# Scale subject to be about 60% of the height of the background
target_h = int(bg_h * 0.6)
scale = target_h / subj_h
target_w = int(subj_w * scale)
subject_resized = subject_image.resize((target_w, target_h), Image.Resampling.LANCZOS)

# Calculate position to place subject (centered horizontally, bottom aligned with desk)
# Assuming desk is around bottom 30% of the image
x = (bg_w - target_w) // 2
y = bg_h - target_h - int(bg_h * 0.15)  # slightly above bottom

print("Compositing...")
# Composite
bg_image.paste(subject_resized, (x, y), subject_resized)

# Save as RGB
print("Saving...")
final_image = bg_image.convert("RGB")
final_image.save(output_path, "JPEG", quality=95)
print("Done!")
