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-p1","hf_20260529_152142_d0381ba4-54e8-4cec-a978-82462a1d56fb.png"),
 ("boy-p2","hf_20260529_152147_b331c5e0-f7c7-441e-ae38-5a50ddaf1216.png"),
 ("boy-p3","hf_20260529_152153_47b09e66-f5cb-4b7c-ab4c-1981e7bd3bd9.png"),
 ("boy-p4","hf_20260529_152159_de0818ce-f127-462b-afba-0f03665154b2.png"),
 ("boy-p5","hf_20260529_152207_3450aade-7279-414b-a5b4-f6bc0cb78864.png"),
 ("boy-p6","hf_20260529_152215_d1b9b777-0225-4885-b5a2-08842809bb08.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",(6*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\grade_boys_cut.png"); print("sheet ready")
