#!/usr/bin/env python3
"""Generate deal graphic for Die weiße Burg."""
from PIL import Image, ImageDraw, ImageFont
import urllib.request, io

# 1. Amazon-Bild mit hoher Auflösung laden
print("Loading Amazon image...")
url = "https://m.media-amazon.com/images/I/51V2DHl3n7L._SL1500_.jpg"
box = Image.open(io.BytesIO(urllib.request.urlopen(url).read())).convert('RGBA')
print(f"  Original size: {box.size}")

# 2. Weiße Ränder entfernen
import numpy as np
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. Skalieren (max 480px Höhe)
scale = 480.0 / box.size[1]
box = box.resize((int(box.size[0]*scale), 480), Image.LANCZOS)
print(f"  After scale: {box.size}")

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

# 5. Hintergrund
bg = Image.open('/home/hermes/.hermes/image_cache/img_79ed85dc27f2.jpg').convert('RGBA')
W, H = bg.size
print(f"  Background: {W}x{H}")
canvas = Image.new('RGBA', (W, H), (0,0,0,0))
canvas.paste(bg, (0,0))

# 6. Box positionieren
canvas.paste(box, (100, 115), box)

# 7. Footer
draw = ImageDraw.Draw(canvas)
font_footer = ImageFont.truetype('/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf', 14)
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. Speichern
output = '/home/hermes/workspace/weisse_burg_deal.png'
canvas.save(output, 'PNG')
print(f"\nSaved: {output} ({W}x{H})")
