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
B=[
 ("boy-pose-wave","hf_20260529_152456_18b17b64-6a7e-4195-a529-8704fb3c3fa8.png"),
 ("boy-pose-point","hf_20260529_152502_e5bd5419-7841-436d-a6ee-856dc07191a2.png"),
 ("boy-pose-thumbsup","hf_20260529_152508_bcc16cb9-3f79-47e1-b5ed-9f327fe7bdf0.png"),
 ("boy-pose-sit","hf_20260529_152516_6c10f1e2-ec5e-47cb-b216-3fa46ca53872.png"),
 ("boy-pose-jump","hf_20260529_152523_750bd29c-aec3-4b04-8314-3db2383cd3d3.png"),
]
rows=[]
for cid,fn in B:
    name=f"ags-math-char-{cid}"; jid=fn.split("_")[-1].replace(".png","")
    webp=CH/f"{name}.webp"; tmp=CHS/("_src_"+cid+".png")
    if not fetch(base+fn,tmp): print("!! FETCH FAILED",name,flush=True); continue
    cut=remove(Image.open(tmp).convert("RGBA")); cut.save(CHS/f"{name}.png",optimize=True); tmp.unlink()
    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:
        for e in m["characters"]:
            if e["id"]==cid: e["file_size_kb"]=kb; e["higgsfield_job_id"]=jid
        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",(5*200,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((188,176),Image.LANCZOS)
    x=i*200; cv.paste(im,(x+(200-im.width)//2,22+(176-im.height)//2),im)
    dr.rectangle([x,0,x+199,18],fill=(20,20,20)); dr.text((x+3,4),cid,fill=(255,255,0))
cv.save(r"C:\allgifted\logo-reveal\boy_poses_cut.png"); print("sheet ready")
