import cv2, numpy as np, urllib.request
from PIL import Image
from pathlib import Path

d = Path(r"C:\allgifted\mathapi11v2\public\assets\math\chars")
base = "https://d8j0ntlcm91z4.cloudfront.net/user_3ENYB9gUptp5V9uUGoiaDV631pi/"
TARGET = 120*1024

JOBS = [
 ("ags-math-char-carrot.png",     "hf_20260529_090647_5af1f35c-7573-4c3d-bbd8-48fcfc296877.png"),
 ("ags-math-char-lucky.png",      "hf_20260529_093458_fbedbba0-d334-4586-a887-cd6b36adf7d2.png"),
 ("ags-math-char-mimi.png",       "hf_20260529_094103_c5f613cf-018f-4903-bd06-1d10809ca616.png"),
 ("ags-math-char-snail-small.png","hf_20260529_090716_40101b51-2e67-44a3-b058-6f3aa182ee3e.png"),
 ("ags-math-char-snail-big.png",  "hf_20260529_090722_e0b43514-4b54-4636-bc69-d0391133c791.png"),
 ("ags-math-char-rabbit.png",     "hf_20260529_090741_65948944-f0ce-4df9-99a8-37db8269a0f5.png"),
 ("ags-math-char-mouse.png",      "hf_20260529_090900_f885a62d-b4ce-4973-8e97-c3191cf94a2f.png"),
 ("ags-math-char-dragonfly.png",  "hf_20260529_092614_9880e3f8-bc21-4d86-b4f5-96c905cf7b66.png"),
 ("ags-math-char-bear.png",       "hf_20260529_090938_0060e0fa-01d0-44c1-94ad-c660d42bb0e5.png"),
]

def key_background(bgr, tol=48):
    h, w = bgr.shape[:2]
    mask = np.zeros((h+2, w+2), np.uint8)
    # FIXED_RANGE: compare each pixel to the SEED colour (not its neighbour),
    # so the fill can't creep across gradients / broken outlines into the subject.
    flags = 8 | (255 << 8) | cv2.FLOODFILL_MASK_ONLY | cv2.FLOODFILL_FIXED_RANGE
    work = bgr.copy()
    for seed in [(0,0),(w-1,0),(0,h-1),(w-1,h-1)]:
        cv2.floodFill(work, mask, seed, 0, (tol,tol,tol), (tol,tol,tol), flags)
    bg = mask[1:-1, 1:-1] > 0
    # eat 1px into the edge to kill the light halo
    bgd = cv2.dilate(bg.astype(np.uint8), np.ones((3,3),np.uint8), iterations=1).astype(bool)
    alpha = np.where(bgd, 0, 255).astype(np.uint8)
    return alpha

for fname, url in JOBS:
    tmp = d / ("_tmp_" + fname)
    urllib.request.urlretrieve(base + url, tmp)
    bgr = cv2.imread(str(tmp))
    alpha = key_background(bgr)
    rgb = cv2.cvtColor(bgr, cv2.COLOR_BGR2RGB)
    im = Image.fromarray(rgb)
    # palette PNG (255 colours) + index 255 reserved as transparent -> small + hard alpha
    p = im.convert("P", palette=Image.ADAPTIVE, colors=255)
    arr = np.array(p)
    arr[alpha == 0] = 255
    p2 = Image.fromarray(arr, mode="P")
    p2.putpalette(p.getpalette()[:255*3] + [0, 0, 0])
    out = d / fname
    p2.save(out, optimize=True, transparency=255)
    tmp.unlink()
    transp = int((alpha == 0).sum())
    print(f"{fname:30s} {out.stat().st_size/1024:6.1f}KB  transparent_px={transp:>9}  mode={p2.mode}")
