#!/usr/bin/env python3
"""Generates the animated email banner GIFs (aurora + confetti) for every colour theme.
Run once on a dev machine:  python3 tools/make_banners.py   (needs Pillow). Output: public/assets/email/<theme>-<type>.gif
"""
import math, random, os, sys
from PIL import Image, ImageDraw, ImageFilter, ImageChops

THEMES = {  # key: (primary, accent)  -- keep in sync with Templates::themes()
    'brint': ('#0b5254', '#f4ba2a'), 'royal': ('#1a4fa0', '#f5a524'), 'emerald': ('#0f6b46', '#f2c14e'),
    'crimson': ('#9b1c31', '#f6c453'), 'violet': ('#5b2a9e', '#ffb84d'), 'sunset': ('#c2410c', '#fbbf24'),
    'midnight': ('#111827', '#38bdf8'), 'rose': ('#be185d', '#fcd34d'),
}
W, H, N = 600, 240, 10
OUT = os.path.join(os.path.dirname(__file__), '..', 'public', 'assets', 'email')

def rgb(h): h = h.lstrip('#'); return tuple(int(h[i:i+2], 16) for i in (0, 2, 4))
def mix(a, b, r): return tuple(int(a[i]*(1-r)+b[i]*r) for i in range(3))

def base(c1, c2):
    im = Image.new('RGB', (W, H)); px = im.load()
    for y in range(H):
        for x in range(W):
            t = min(1, max(0, (x/W*0.75 + y/H*0.25)))
            px[x, y] = mix(c1, c2, t)
    return im

def aurora(theme, primary, accent):
    p, a = rgb(primary), rgb(accent)
    dark = mix(p, (4, 14, 20), 0.80); mid = mix(p, (4, 14, 20), 0.52)
    bg = base(dark, mid)
    rnd = random.Random(theme)
    stars = [(rnd.randint(0, W), rnd.randint(0, H), rnd.uniform(0, 6.28), rnd.choice([1, 1, 2])) for _ in range(34)]
    frames = []
    for f in range(N):
        t = f / N * 2 * math.pi
        layer = Image.new('RGB', (W, H), (0, 0, 0))
        d = ImageDraw.Draw(layer)
        blobs = [(W*0.78 + 70*math.cos(t), H*0.35 + 40*math.sin(t), 120, mix(a, (0, 0, 0), 0.45)),
                 (W*0.30 + 90*math.sin(t + 1), H*0.80 + 30*math.cos(t), 140, mix(p, (255, 255, 255), 0.18)),
                 (W*0.55 + 110*math.cos(t + 2.2), H*0.15 + 30*math.sin(t + 1), 100, mix(p, a, 0.35))]
        for (x, y, r, col) in blobs: d.ellipse((x-r, y-r*0.7, x+r, y+r*0.7), fill=col)
        layer = layer.filter(ImageFilter.GaussianBlur(46)).point(lambda v: int(v * 0.42))
        im = ImageChops.add(bg, layer)  # subtle light-on-dark glow so white text stays readable
        dd = ImageDraw.Draw(im)
        for (x, y, ph, sz) in stars:
            k = ((math.sin(t * 1 + ph) + 1) / 2) ** 0.6
            if k > 0.2:
                col = mix(rgb('#ffffff'), a, 0.25); col = mix(mid, col, k)
                dd.ellipse((x - sz*(0.5+k), y - sz*(0.5+k), x + sz*(0.5+k), y + sz*(0.5+k)), fill=col)
                if sz == 2 and k > 0.75:  # twinkle cross
                    dd.line((x-7, y, x+7, y), fill=col); dd.line((x, y-7, x, y+7), fill=col)
        frames.append(im)
    return frames

def confetti(theme, primary, accent):
    p, a = rgb(primary), rgb(accent)
    bg = base(mix(a, (0, 0, 0), 0.52), mix(p, (0, 0, 0), 0.45))
    rnd = random.Random(theme + 'c')
    cols = [a, (255, 255, 255), mix(a, (255, 255, 255), .5), mix(p, (255, 255, 255), .45), (255, 120, 150)]
    bits = [(rnd.randint(0, W), rnd.uniform(0, H), rnd.uniform(0.6, 1.4), rnd.choice(cols), rnd.choice('rc'), rnd.randint(4, 8), rnd.uniform(0, 6.28)) for _ in range(46)]
    frames = []
    for f in range(N):
        im = bg.copy(); d = ImageDraw.Draw(im)
        for (x, y0, sp, col, shape, sz, ph) in bits:
            y = (y0 + f / N * H * sp * 1.0) % (H + 20) - 10
            xx = x + 14 * math.sin(f / N * 2 * math.pi + ph)
            if shape == 'c': d.ellipse((xx, y, xx+sz, y+sz), fill=col)
            else:
                w = sz * (0.4 + abs(math.cos(f / N * 2 * math.pi * 2 + ph)))
                d.rectangle((xx, y, xx+w, y+sz*0.6), fill=col)
        frames.append(im)
    return frames

def save(frames, path):
    q = [f.quantize(colors=48, method=Image.Quantize.MEDIANCUT, dither=Image.Dither.NONE) for f in frames]
    q[0].save(path, save_all=True, append_images=q[1:], duration=130, loop=0, optimize=True, disposal=1)
    return os.path.getsize(path)

if __name__ == '__main__':
    os.makedirs(OUT, exist_ok=True)
    for key, (p, a) in THEMES.items():
        for typ, fn in (('aurora', aurora), ('confetti', confetti)):
            size = save(fn(key, p, a), os.path.join(OUT, f'{key}-{typ}.gif'))
            print(f'{key}-{typ}.gif  {size//1024} KB')
