from PIL import Image
import os, statistics

SRC="/Users/dontrell/Sites/abk-v2-funnel/01-fe-sales/assets/marketplaces"
DST="/Users/dontrell/Sites/abk-v2-funnel/vsl-deck/assets/marketplaces"
OUT=256
names=["etsy","gumroad","amazon","apple","payhip","whop"]

for n in names:
    im=Image.open(os.path.join(SRC,n+".png")).convert("RGBA")
    w,h=im.size; src=im.load()
    # inside = the icon tile itself (original alpha), outside = transparent corners
    inside=[[src[x,y][3]>=128 for y in range(h)] for x in range(w)]
    # sample the tile's own border colour, ignoring anything outside the tile
    ms=[];cols=[]
    for x in range(w):
        for y in range(h):
            if not inside[x][y]: continue
            edge = x<2 or y<2 or x>w-3 or y>h-3
            # also treat pixels adjacent to an outside pixel as tile edge
            if not edge:
                for dx,dy in ((1,0),(-1,0),(0,1),(0,-1)):
                    nx,ny=x+dx,y+dy
                    if 0<=nx<w and 0<=ny<h and not inside[nx][ny]: edge=True;break
            if edge:
                r,g,b=src[x,y][:3]; ms.append(min(r,g,b)); cols.append((r,g,b))
    if not ms: ms=[255]; cols=[(255,255,255)]
    m_bg=statistics.median(ms)
    brand=(int(statistics.median([c[0] for c in cols])),
           int(statistics.median([c[1] for c in cols])),
           int(statistics.median([c[2] for c in cols])))
    # does the tile contain a real white GLYPH? that is what makes inversion correct
    inside_n=sum(1 for x in range(w) for y in range(h) if inside[x][y]) or 1
    white_n=sum(1 for x in range(w) for y in range(h)
                if inside[x][y] and min(src[x,y][:3])>235)
    white_frac=white_n/inside_n
    out=Image.new("RGB",(w,h),(255,255,255)); op=out.load()
    if m_bg>200 or white_frac<0.02:
        for x in range(w):
            for y in range(h):
                if not inside[x][y]: continue
                r,g,b=src[x,y][:3]
                op[x,y]=(255,255,255) if min(r,g,b)>200 else (r,g,b)
        mode="kept as-authored (white_frac %.2f, m_bg %d)"%(white_frac,m_bg)
    else:
        den=max(1,255-m_bg)
        for x in range(w):
            for y in range(h):
                if not inside[x][y]: continue          # outside the tile stays white
                r,g,b=src[x,y][:3]
                t=(min(r,g,b)-m_bg)/den
                t=0.0 if t<0 else (1.0 if t>1 else t)
                # gradient tiles leave a halo: snap near-background to pure white,
                # then rescale so the glyph and its antialiased edge keep full strength
                FLOOR=0.22
                t = 0.0 if t<FLOOR else (t-FLOOR)/(1.0-FLOOR)
                op[x,y]=(int(255+(brand[0]-255)*t),int(255+(brand[1]-255)*t),int(255+(brand[2]-255)*t))
        mode="inverted, brand rgb%s (white_frac %.2f)"%(brand,white_frac)
    out.resize((OUT,OUT),Image.LANCZOS).save(os.path.join(DST,n+".png"))
    print("%-9s %s"%(n,mode))
