from PIL import Image, ImageDraw, ImageFont, ImageFilter
import math
FR='tmp/fonts/DejaVuSans.ttf'; FB='tmp/fonts/DejaVuSans-Bold.ttf'
fr=lambda s: ImageFont.truetype(FR,s); fb=lambda s: ImageFont.truetype(FB,s)

card = Image.open('files/pepperoni-slice-300dpi.png').convert('RGBA'); W,H = card.size
ALPHA = card.split()[3].load()
tan22 = math.tan(math.radians(22.5))
def inside(x,y,m=0):
    for dx,dy in ((0,0),(m,0),(-m,0),(0,m),(0,-m)):
        px,py = int(x+dx), int(y+dy)
        if px<0 or py<0 or px>=W or py>=H or ALPHA[px,py] < 200: return False
    return True

# ---------------- arc banner: crust edge to crust edge, big ----------------
text = "Thank you for your business"
SPAN = math.radians(36.5)            # from one cut edge to the other, with a hair to spare
cx, cy = W/2, H+40
R0 = H-165
probe = fr(100); total100 = sum(probe.getlength(c) for c in text)
fs = max(20, int(round(100 * (SPAN*R0) / total100)))
font = fr(fs)
adv = [font.getlength(c) for c in text]
span = sum(adv)/R0

best=None
R = H-320
while R <= H-120:
    sp = sum(adv)/R
    theta = -math.pi/2 - sp/2
    boxes=[]; ok=True
    for ch,aw in zip(text,adv):
        if ch!=' ':
            bb=font.getbbox(ch); gw,gh=max(1,bb[2]-bb[0]),max(1,bb[3]-bb[1])
            a0 = theta+(aw/2)/R
            gx = cx+R*math.cos(a0); gy = cy+R*math.sin(a0)
            hw = gh/2*abs(math.cos(a0))+gw/2*abs(math.sin(a0))
            hh = gh/2*abs(math.sin(a0))+gw/2*abs(math.cos(a0))
            boxes.append((ch,gx,gy,bb,gw,gh,a0))
            for sx,sy in ((gx-hw,gy-hh),(gx+hw,gy-hh),(gx-hw,gy+hh),(gx+hw,gy+hh)):
                if not inside(sx,sy,10): ok=False
        theta += aw/R
    if ok and (best is None or R > best[0]): best=(R,boxes,sp)
    R += 3

R, boxes, span = best
print('banner %.0f pt, spans %.0f deg of crust, radius %d (%.0f px in from the edge)' % (fs, math.degrees(span), R, H-R))
layer=Image.new('RGBA',(W,H),(0,0,0,0))
for ch,gx,gy,bb,gw,gh,a0 in boxes:
    g=Image.new('RGBA',(gw+8,gh+8),(0,0,0,0))
    ImageDraw.Draw(g).text((4-bb[0],4-bb[1]),ch,font=font,fill=(26,19,15,255))
    g=g.rotate(-(math.degrees(a0)+90),resample=Image.BICUBIC,expand=True)
    layer.alpha_composite(g,(int(gx-g.width/2),int(gy-g.height/2)))

slice_mask = card.split()[3]
rib = layer.split()[3].filter(ImageFilter.MaxFilter(41)).filter(ImageFilter.GaussianBlur(7))
rib = Image.composite(rib, Image.new('L',(W,H),0), slice_mask.point(lambda v: 255 if v>200 else 0))
card.alpha_composite(Image.composite(Image.new('RGBA',(W,H),(255,250,236,236)),Image.new('RGBA',(W,H),(0,0,0,0)),rib))
card.alpha_composite(layer)

# ---------------- message box ----------------
raw = ("Choose another pizza for your team or __pass it on__ ++to a business that needs better IT++")
words=[]; i=0
while i < len(raw):
    if raw.startswith('**', i):
        j=raw.index('**', i+2); words += [(w,'bold') for w in raw[i+2:j].split()]; i=j+2
    elif raw.startswith('__', i):
        j=raw.index('__', i+2); words += [(w,'under') for w in raw[i+2:j].split()]; i=j+2
    elif raw.startswith('++', i):
        j=raw.index('++', i+2); words += [(w,'purple') for w in raw[i+2:j].split()]; i=j+2
    elif raw[i]==' ': i+=1
    else:
        j=i
        while j < len(raw) and raw[j] != ' ':
            if raw.startswith('**', j) or raw.startswith('__', j) or raw.startswith('++', j): break
            j+=1
        words += [(w,'norm') for w in raw[i:j].split()]; i=j

size=60; R_=ImageFont.truetype('tmp/fonts/ArchivoBlack.ttf',size); B_=R_ ; space=R_.getlength(' ')
PADX, PADY, MARGIN = 50, 45, 56
centre_y = H*0.315
def wrap(maxw):
    lines, cur, curw = [], [], 0.0
    for w,st in words:
        ww=(B_ if st=='bold' else R_).getlength(w)
        add = ww if not cur else space+ww
        if curw+add > maxw and cur:
            lines.append(cur); cur=[(w,st,ww)]; curw=ww
        else:
            cur.append((w,st,ww)); curw+=add
    if cur: lines.append(cur)
    return lines
maxw = W*0.52
while maxw > W*0.18:
    lines = wrap(maxw); lh = int(size*1.28); bh = len(lines)*lh
    bw = max(sum(w for _,_,w in ln)+space*(len(ln)-1) for ln in lines)
    box_w = bw+2*PADX; box_bottom = centre_y+bh/2+PADY
    if box_w/2 <= (H-box_bottom)*tan22 - MARGIN: break
    maxw -= 8
cx0,cx1 = W/2-bw/2-PADX, W/2+bw/2+PADX
cy0,cy1 = centre_y-bh/2-PADY, centre_y+bh/2+PADY
p=Image.new('RGBA',(W,H),(0,0,0,0))
ImageDraw.Draw(p).rounded_rectangle([cx0,cy0,cx1,cy1],radius=30,fill=(255,252,242,246))
card.alpha_composite(p); d=ImageDraw.Draw(card)
d.rounded_rectangle([cx0,cy0,cx1,cy1],radius=30,outline=(0,0,0,30),width=3)
starty = centre_y-bh/2+lh/2
for n,line in enumerate(lines):
    lw = sum(w for _,_,w in line)+space*(len(line)-1); x = W/2-lw/2; y = starty+n*lh
    for w,st,ww in line:
        fnt = B_ if st=='bold' else R_
        col = (94,35,157,255) if st in ('under','purple') else (52,44,36,255)
        d.text((x,y), w, font=fnt, fill=col, anchor='lm')
        if st=='under':
            d.line([x,y+size*0.44,x+ww,y+size*0.44], fill=(94,35,157,255), width=max(5,size//12))
        x += ww+space

# ---------------- QR ----------------
qr = 330; qy = int(cy1+112)
b=Image.new('RGBA',(W,H),(0,0,0,0))
ImageDraw.Draw(b).rounded_rectangle([W/2-qr/2-20,qy-20,W/2+qr/2+20,qy+qr+20],radius=14,fill=(255,252,242,255))
card.alpha_composite(b)
card.paste(Image.open('tmp/qr.png').convert('RGB').resize((qr,qr),Image.LANCZOS),(int(W/2-qr/2),qy))

# ---------------- note ----------------
l1,l2 = "Let us know","scan the QR code"; lf=fb(44)
lw = max(lf.getlength(l1),lf.getlength(l2))
ly = qy+qr+112
lb=Image.new('RGBA',(W,H),(0,0,0,0))
ImageDraw.Draw(lb).rounded_rectangle([W/2-lw/2-32,ly-44,W/2+lw/2+32,ly+82],radius=28,fill=(255,252,242,244))
card.alpha_composite(lb); d=ImageDraw.Draw(card)
d.text((W/2,ly-10),l1,font=lf,fill=(94,35,157,255),anchor='mm')
d.text((W/2,ly+50),l2,font=lf,fill=(94,35,157,255),anchor='mm')

# hard rule check: nothing may sit outside the pizza
bad=[]
for nm,(x0,y0,x1,y1) in {'box':(cx0,cy0,cx1,cy1),'qr':(W/2-qr/2-20,qy-20,W/2+qr/2+20,qy+qr+20),
                          'note':(W/2-lw/2-32,ly-44,W/2+lw/2+32,ly+82)}.items():
    for sx,sy in ((x0,y0),(x1,y0),(x0,y1),(x1,y1),((x0+x1)/2,y1)):
        if not inside(sx,sy,4): bad.append((nm,sx,sy))
print('elements outside the pizza border:', bad if bad else 'none')

card.save('files/missing-piece-card-300dpi.png'); card.save('files/missing-piece-card-print.pdf',resolution=300.0)
prev=Image.new('RGB',(W,H),(250,250,250)); prev.paste(card,(0,0),card); prev.thumbnail((900,1200),Image.LANCZOS)
prev.save('files/missing-piece-card-preview.jpg',quality=93)
