#!/usr/bin/env python3
from PIL import Image, ImageDraw, ImageFont
import urllib.request, io, numpy as np

# 1. Load Amazon image (SL1500 highest res)
url = 'https://m.media-amazon.com/images/I/41nsjnQfLyL._SL1500_.jpg'
print(f"Loading image from: {url}")
img_data = urllib.request.urlopen(url).read()
box = Image.open(io.BytesIO(img_data)).convert('RGBA')
print(f"Original size: {box.size}")

# 2. Remove white borders
pixels = np.array(box)
mask = (pixels[:,:,0] > 245) & (pixels[:,:,1] > 245) & (pixels[:,:,2] > 245)
pixels[mask, 3] = 0
box = Image.fromarray(pixels, 'RGBA')
bbox = box.getbbox()
if bbox:
    box = box.crop(bbox)
    print(f"After crop: {box.size}")

# 3. Scale max 480px height
scale = 480.0 / box.size[1]
new_size = (int(box.size[0] * scale), 480)
box = box.resize(new_size, Image.LANCZOS)
print(f"After scale: {box.size}")

# 4. Rotate -10 degrees
box = box.rotate(-10, resample=Image.BICUBIC, expand=True, fillcolor=(0,0,0,0))
print(f"After rotate: {box.size}")

# 5. Load background
bg = Image.open('/home/hermes/.hermes/image_cache/img_79ed85dc27f2.jpg').convert('RGBA')
W, H = bg.size
print(f"Background: {bg.size}")

canvas = Image.new('RGBA', (W, H), (0,0,0,0))
canvas.paste(bg, (0,0))

# 6. Position box (left side, inside red area)
canvas.paste(box, (100, 115), box)
print("Pasted at (100, 115)")

# 7. Footer
draw = ImageDraw.Draw(canvas)
try:
    font_footer = ImageFont.truetype('/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf', 14)
except:
    font_footer = ImageFont.load_default()

footer = 'Brettspiel-News.de \u00b7 (C) liegt beim jeweiligen Rechteinhaber'
fw = draw.textlength(footer, font=font_footer)
draw.text(((W - fw) // 2, H - 22), footer, fill=(255, 255, 255, 80), font=font_footer)

# 8. Save
output_path = '/home/hermes/workspace/dune_uprising_sale_2026-06-20.png'
canvas.save(output_path, 'PNG')
print(f"Saved to: {output_path}")
