#!/usr/bin/env python3
"""Plappi ad-creative renderer. Overlays headline/sub/CTA/badge + logo on a base image.
Brand: navy scrim + white headline + coral/yellow accent. Output 1080x1080 (or given size).
"""
from PIL import Image, ImageDraw, ImageFont, ImageFilter
import os, re

_EMOJI = re.compile("[\U0001F000-\U0001FAFF\U00002600-\U000026FF\U00002700-\U000027BF\U0001F1E6-\U0001F1FF\U00002B00-\U00002BFF️]")
def _clean(t):
    return _EMOJI.sub('', t).replace('  ', ' ').strip() if t else t

HERE = os.path.dirname(os.path.abspath(__file__))
NAVY = (24, 32, 56)
CORAL = (255, 107, 74)
YELLOW = (255, 209, 102)
WHITE = (255, 255, 255)
SOFT = (224, 230, 240)

def _font(bold, size):
    p = ('/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf' if bold
         else '/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf')
    try: return ImageFont.truetype(p, size)
    except Exception: return ImageFont.load_default()

def _cover(im, size):
    tw, th = size; iw, ih = im.size
    s = max(tw/iw, th/ih)
    im = im.resize((int(iw*s)+1, int(ih*s)+1), Image.LANCZOS)
    x = (im.width - tw)//2; y = (im.height - th)//2
    return im.crop((x, y, x+tw, y+th))

def _wrap(draw, text, font, maxw):
    words = text.split(); lines=[]; cur=''
    for w in words:
        t=(cur+' '+w).strip()
        if draw.textlength(t, font=font) <= maxw: cur=t
        else:
            if cur: lines.append(cur)
            cur=w
    if cur: lines.append(cur)
    return lines

def creative(base, out, headline, sub=None, cta=None, badge=None,
             size=(1080,1080), scrim='bottom', accent=CORAL, logo=True):
    im = Image.open(os.path.join(HERE, base)).convert('RGB')
    im = _cover(im, size).convert('RGBA')
    W, H = size
    # scrim gradient for legibility
    grad = Image.new('L', (1, H), 0)
    for y in range(H):
        if scrim == 'bottom':
            a = int(255 * max(0, (y/H - 0.40) / 0.60) ** 1.3) if y/H > 0.40 else 0
        else:  # top
            a = int(255 * max(0, (0.55 - y/H) / 0.55) ** 1.3)
        grad.putpixel((0, y), min(235, a))
    grad = grad.resize((W, H))
    overlay = Image.new('RGBA', (W, H), NAVY + (0,))
    overlay.putalpha(grad)
    im = Image.alpha_composite(im, overlay)
    d = ImageDraw.Draw(im)
    M = 70
    # badge (top-left pill)
    if badge:
        bf = _font(True, 34)
        bw = d.textlength(badge, font=bf)
        d.rounded_rectangle([M, M, M+bw+44, M+58], radius=29, fill=accent)
        d.text((M+22, M+12), badge, font=bf, fill=NAVY)
    # logo top-right
    if logo:
        try:
            lg = Image.open(os.path.join(HERE, 'plappi_06.png')).convert('RGBA')
            lg.thumbnail((190, 120))
            im.alpha_composite(lg, (W-lg.width-M, M-6))
        except Exception: pass
    # text block bottom
    hf = _font(True, 70); sf = _font(False, 38)
    hlines = _wrap(d, headline, hf, W-2*M)
    slines = _wrap(d, sub, sf, W-2*M) if sub else []
    lh = 80; sh = 50; cta_h = 84 if cta else 0
    block = len(hlines)*lh + (24+len(slines)*sh if slines else 0) + (40+cta_h if cta else 0)
    y = H - M - block
    for ln in hlines:
        d.text((M, y), ln, font=hf, fill=WHITE); y += lh
    if slines:
        y += 24
        for ln in slines:
            d.text((M, y), ln, font=sf, fill=SOFT); y += sh
    if cta:
        y += 40; cf=_font(True, 38); cw=d.textlength(cta, font=cf)
        d.rounded_rectangle([M, y, M+cw+72, y+cta_h], radius=42, fill=accent)
        d.text((M+36, y+20), cta, font=cf, fill=NAVY)
    im.convert('RGB').save(os.path.join(HERE, out), quality=92)
    return out

if __name__ == '__main__':
    os.makedirs(os.path.join(HERE, 'creatives'), exist_ok=True)
    creative('plappi_27.jpeg', 'creatives/_test.jpg',
             'Mehr Sprache. Ganz ohne Bildschirm.',
             sub='Plappi bringt Kinder zum aktiven Sprechen — 27 Sprachen.',
             cta='Jetzt auf die Warteliste  →', badge='🚀 Kickstarter · 24. Juni')
    print('wrote creatives/_test.jpg')
