import urllib.request, time, json
from rembg import remove
from PIL import Image, ImageDraw
from pathlib import Path
OB=Path(r"C:\allgifted\mathapi11v2\public\assets\math\objects"); OBS=OB/"source"
TARGET=120*1024; B="https://d8j0ntlcm91z4.cloudfront.net/user_3ENYB9gUptp5V9uUGoiaDV631pi/"
def fetch(u,d):
    for _ in range(5):
        try: urllib.request.urlretrieve(u,d); return True
        except Exception: time.sleep(2)
    return False
OBJ=[
 ("donut",B+"hf_20260529_161945_f59afffb-93cd-4501-ae96-8eadd77c71a7.png"),
 ("pail-bucket",B+"hf_20260529_161950_e6150bcb-6b50-4c86-b13f-29ca7dc5e2fa.png"),
 ("glass-bottle",B+"hf_20260529_161957_5167ba6f-b354-415a-846a-5ef822b28895.png"),
 ("plate-with-cookies",B+"hf_20260529_162003_8335ff14-5eb2-4cea-9827-956b678d5501.png"),
 ("number-train",B+"hf_20260529_162009_7a346d1b-4a56-48fb-a755-38b3f982c575.png"),
 ("traffic-cone",B+"hf_20260529_162014_6714c774-2b73-4680-bdef-fc5662662b81.png"),
 ("street-lamp",B+"hf_20260529_162022_6cacf6c8-4e93-442b-9d5a-f72d575c86a2.png"),
 ("classroom-chair",B+"hf_20260529_162029_a2c3b647-bc26-47e2-8718-1907f97edba9.png"),
 ("building-house",B+"hf_20260529_162035_1b16ce47-eaf2-4a2e-9e7b-b331f0ea1681.png"),
]
rows=[]
for oid,url in OBJ:
    name=f"ags-math-obj-{oid}"; jid=url.split("_")[-1].split(".")[0]
    webp=OB/f"{name}.webp"; tmp=OBS/("_src_"+oid+".png")
    if not fetch(url,tmp): print("!! FETCH FAILED",name,flush=True); continue
    cut=remove(Image.open(tmp).convert("RGBA")); cut.save(OBS/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((oid,jid,round(webp.stat().st_size/1024,1),webp.name)); print(f"{webp.name:34s} {rows[-1][2]:6.1f}KB",flush=True)
mf=OB/"ags_math_objects_manifest.json"; m=json.loads(mf.read_text(encoding="utf-8")); ex={e["id"] for e in m["objects"]}
for oid,jid,kb,fname in rows:
    if oid in ex:
        for e in m["objects"]:
            if e["id"]==oid: e["file_size_kb"]=kb; e["higgsfield_job_id"]=jid
        continue
    m["objects"].append({"id":oid,"filename":fname,"higgsfield_job_id":jid,"file_size_kb":kb,
        "cdn_url":f"https://math.allgifted.com/objects/{fname}","format":"webp","background":"transparent","badge":"none","status":"approved"})
m["count"]=len(m["objects"]); mf.write_text(json.dumps(m,indent=2),encoding="utf-8"); print("objects manifest:",m["count"])
cv=Image.new("RGB",(5*180,2*180),(120,120,120)); dr=ImageDraw.Draw(cv)
for i,(oid,jid,kb,fn) in enumerate(rows):
    im=Image.open(OB/fn).convert("RGBA"); im.thumbnail((168,150),Image.LANCZOS)
    r,c=divmod(i,5); x,y=c*180,r*180
    cv.paste(im,(x+(180-im.width)//2,y+22+(150-im.height)//2),im)
    dr.rectangle([x,y,x+179,y+18],fill=(20,20,20)); dr.text((x+3,y+4),oid,fill=(255,255,0))
cv.save(r"C:\allgifted\logo-reveal\niche_objects_check.png"); print("sheet ready")
