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
# (race-gender, pose, cdn filename)
P=[
 ("chinese-girl","wave","hf_20260529_150337_2c1c146c-f689-4185-a323-0d31384fe6a2.png"),
 ("chinese-boy","wave","hf_20260529_150343_371a4bb1-732d-4118-863f-246d62ca7a64.png"),
 ("malay-girl","wave","hf_20260529_150349_51e22aac-8629-4bdc-824e-d5527c41a583.png"),
 ("malay-boy","wave","hf_20260529_151815_bfcd0f95-54b0-485e-8b39-07815a873b87.png"),
 ("indian-girl","wave","hf_20260529_150404_48d7d855-44ea-492a-95a2-68dd451dea8d.png"),
 ("indian-boy","wave","hf_20260529_150412_47447dc0-b379-4fdc-b0c2-424c3f0c2005.png"),
 ("eurasian-girl","wave","hf_20260529_150417_4c3c587d-3fec-4735-95be-b5f165cf675b.png"),
 ("eurasian-boy","wave","hf_20260529_150423_22610694-9292-4165-87a2-a1a823f31b5e.png"),
 ("chinese-girl","point","hf_20260529_150715_8ebd472c-9574-4a41-b2be-c1e536273b53.png"),
 ("chinese-boy","point","hf_20260529_150724_a4b12134-2698-4329-9320-aecd6ae7d3ba.png"),
 ("malay-girl","point","hf_20260529_150730_2f07b055-6759-4130-81c4-468abc53a671.png"),
 ("malay-boy","point","hf_20260529_150737_822dd7d5-a706-45c1-b3a4-a4ec62782862.png"),
 ("indian-girl","point","hf_20260529_150742_fca6308c-3909-4cbd-8f05-4902ceaf423c.png"),
 ("indian-boy","point","hf_20260529_150749_5188119c-23f9-4024-a3e9-41d6605c2f66.png"),
 ("eurasian-girl","point","hf_20260529_150754_fa5803f0-6e4b-4652-8a73-3a479d0e130e.png"),
 ("eurasian-boy","point","hf_20260529_150802_2182fa0e-892d-4376-933d-ca9a10f09f01.png"),
 ("chinese-girl","thumbsup","hf_20260529_150818_1c18971b-d49a-4ebd-8c1f-febe7d7553f2.png"),
 ("chinese-boy","thumbsup","hf_20260529_150826_7dd8ea29-167d-4ba9-947e-a05aa9d13901.png"),
 ("malay-girl","thumbsup","hf_20260529_150833_fcb320f3-b0d2-493d-baa1-77fbb752abcf.png"),
 ("malay-boy","thumbsup","hf_20260529_150842_3c0480ad-7703-4d69-84b4-508eeda72785.png"),
 ("indian-girl","thumbsup","hf_20260529_150849_cacf356f-c6aa-4ae8-b2ea-6a4f5176402e.png"),
 ("indian-boy","thumbsup","hf_20260529_150855_1ec7e1f3-1dec-4d7c-b171-b473d8e6701d.png"),
 ("eurasian-girl","thumbsup","hf_20260529_150902_fd8ef9e1-027f-41f3-b779-cfce91f3c85b.png"),
 ("eurasian-boy","thumbsup","hf_20260529_150908_8d8b3c35-a2c8-4500-b5be-38960bdda4b5.png"),
 ("chinese-girl","sit","hf_20260529_150917_79d4c722-cbc6-4797-9b50-f3b64f2d898a.png"),
 ("chinese-boy","sit","hf_20260529_150924_7d8cb149-a802-4599-9396-0f52af4e974e.png"),
 ("malay-girl","sit","hf_20260529_150929_720139aa-2cf1-4e59-80e0-f9a2a4694e67.png"),
 ("malay-boy","sit","hf_20260529_150935_80fa6d40-e7e0-4f67-8fa4-92e5aea54028.png"),
 ("indian-girl","sit","hf_20260529_150940_ffa59533-f42d-44c7-90e7-671ebe3f44d0.png"),
 ("indian-boy","sit","hf_20260529_150946_2feae17f-a07b-434b-9a1c-3913a3c92000.png"),
 ("eurasian-girl","sit","hf_20260529_150954_9dec4951-c107-4211-a405-d8d5c5baf6a7.png"),
 ("eurasian-boy","sit","hf_20260529_151000_fb80025c-fdd5-4647-9958-7ca70b8b97f6.png"),
 ("chinese-girl","jump","hf_20260529_151007_705b02bd-4734-4b13-9a54-48eee7b61d9e.png"),
 ("chinese-boy","jump","hf_20260529_151013_a7967c5b-f08e-4ea4-9ec5-3910df6d4b95.png"),
 ("malay-girl","jump","hf_20260529_151022_e404a7ae-ac22-499f-9b7a-9ea360e7dbab.png"),
 ("malay-boy","jump","hf_20260529_151029_82ff3cff-6b31-4736-afca-9550afda1d8e.png"),
 ("indian-girl","jump","hf_20260529_151035_6deede61-da7e-4104-89cf-303874efaa45.png"),
 ("indian-boy","jump","hf_20260529_151041_4475327a-1ecb-4326-a0c1-57b99dea7a4a.png"),
 ("eurasian-girl","jump","hf_20260529_151049_a3121764-e296-42e9-9c47-00c58319e96a.png"),
 ("eurasian-boy","jump","hf_20260529_151055_92e4c7bd-8556-47db-b679-1971a2c0d518.png"),
]
rows=[]
for rg,pose,fn in P:
    cid=f"kid-{rg}-pose-{pose}"; name=f"ags-math-char-{cid}"
    jid=fn.split("_")[-1].replace(".png","")
    webp=CH/f"{name}.webp"
    if webp.exists():
        rows.append((cid,jid,round(webp.stat().st_size/1024,1),webp.name,rg,pose)); print(f"{webp.name:46s} (exists)",flush=True); continue
    tmp=CHS/("_src_"+cid+".png")
    if not fetch(base+fn,tmp): print(f"!! 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,rg,pose))
    print(f"{webp.name:46s} {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,rg,pose 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"])
# contact sheet: 8 rows (race-gender) x 5 cols (pose)
RG=["chinese-girl","chinese-boy","malay-girl","malay-boy","indian-girl","indian-boy","eurasian-girl","eurasian-boy"]
PO=["wave","point","thumbsup","sit","jump"]
cell=200; cv=Image.new("RGB",(len(PO)*cell, len(RG)*cell),(120,120,120)); dr=ImageDraw.Draw(cv)
idx={(r,p):f"ags-math-char-kid-{r}-pose-{p}.webp" for r in RG for p in PO}
for ri,r in enumerate(RG):
    for ci,p in enumerate(PO):
        f=CH/idx[(r,p)]
        if not f.exists(): continue
        im=Image.open(f).convert("RGBA"); im.thumbnail((cell-8,cell-26),Image.LANCZOS)
        x,y=ci*cell,ri*cell
        cv.paste(im,(x+(cell-im.width)//2,y+20+(cell-20-im.height)//2),im)
        dr.rectangle([x,y,x+cell-1,y+16],fill=(20,20,20)); dr.text((x+3,y+3),f"{r[:10]} {p}",fill=(255,255,0))
cv.save(r"C:\allgifted\logo-reveal\kid_poses_check.png"); print("sheet ready")
