import urllib.request, time, json
from rembg import remove
from PIL import Image, ImageDraw
from pathlib import Path
CH=Path(r"C:\allgifted\mathapi11v2\public\assets\math\chars"); CHS=CH/"source"
base="https://d8j0ntlcm91z4.cloudfront.net/user_3ENYB9gUptp5V9uUGoiaDV631pi/"; TARGET=120*1024
def fetch(u,d):
    for _ in range(5):
        try: urllib.request.urlretrieve(u,d); return True
        except Exception: time.sleep(2)
    return False
KIDS=[
 ("kid-chinese-girl","77678cd0","hf_20260529_145903_77678cd0-cdb2-496d-99d8-d0ffc048edef.png"),
 ("kid-chinese-boy","85a9dc18","hf_20260529_145908_85a9dc18-1acb-487f-89c7-a7816c2e37fa.png"),
 ("kid-malay-girl","97bcfb6c","hf_20260529_145915_97bcfb6c-8607-43d3-8cc3-53fe2dc85ea9.png"),
 ("kid-malay-boy","06de418e","hf_20260529_145921_06de418e-6a5a-4d54-9e52-46671b3e9251.png"),
 ("kid-indian-girl","468cdea6","hf_20260529_145928_468cdea6-84fa-45d4-a0f6-1c8f2946e0d3.png"),
 ("kid-indian-boy","5a709561","hf_20260529_145934_5a709561-a237-4ee6-bd34-26e6b0c212e6.png"),
 ("kid-eurasian-girl","ab781e58","hf_20260529_145939_ab781e58-091a-4e91-82fa-2f24b4f2054a.png"),
 ("kid-eurasian-boy","b18fc94d","hf_20260529_145948_b18fc94d-fe95-47b7-a7a2-da8c5c85f3d4.png"),
]
rows=[]
for cid,jid,fn in KIDS:
    name=f"ags-math-char-{cid}"; tmp=CHS/("_src_"+cid+".png"); fetch(base+fn,tmp)
    cut=remove(Image.open(tmp).convert("RGBA")); cut.save(CHS/f"{name}.png",optimize=True); tmp.unlink()
    webp=CH/f"{name}.webp"
    for q in (90,86,82,78):
        cut.save(webp,"WEBP",quality=q,lossless=False)
        if webp.stat().st_size<=TARGET: break
    rows.append((cid,jid,round(webp.stat().st_size/1024,1),webp.name)); print(f"{webp.name:34s} {rows[-1][2]:6.1f}KB",flush=True)
mf=CH/"ags_math_characters_manifest.json"; m=json.loads(mf.read_text(encoding="utf-8")); ex={e["id"] for e in m["characters"]}
for cid,jid,kb,fname in rows:
    if cid in ex: continue
    m["characters"].append({"id":cid,"filename":fname,"higgsfield_job_id":jid,"file_size_kb":kb,
        "cdn_url":f"https://math.allgifted.com/chars/{fname}","format":"webp","background":"transparent","badge":"none","status":"approved"})
m["count"]=len(m["characters"]); mf.write_text(json.dumps(m,indent=2),encoding="utf-8"); print("chars manifest:",m["count"])
cv=Image.new("RGB",(4*210,2*210),(120,120,120)); dr=ImageDraw.Draw(cv)
for i,(cid,jid,kb,fn) in enumerate(rows):
    im=Image.open(CH/fn).convert("RGBA"); im.thumbnail((196,176),Image.LANCZOS)
    r,c=divmod(i,4); x,y=c*210,r*210
    cv.paste(im,(x+(210-im.width)//2,y+22+(176-im.height)//2),im)
    dr.rectangle([x,y,x+209,y+18],fill=(20,20,20)); dr.text((x+3,y+4),cid.replace("kid-",""),fill=(255,255,0))
cv.save(r"C:\allgifted\logo-reveal\kids_check.png"); print("sheet ready")
