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
def fetch(u,d):
    for _ in range(5):
        try: urllib.request.urlretrieve(u,d); return True
        except Exception: time.sleep(2)
    return False
B="https://d8j0ntlcm91z4.cloudfront.net/user_3ENYB9gUptp5V9uUGoiaDV631pi/"
OBJ=[
 ("watermelon",B+"hf_20260529_154740_557549da-0611-4b6c-90c1-19caa6109f7a.png"),
 ("giraffe-toy",B+"hf_20260529_154747_414bd50d-a986-4436-8c09-21995a301a14.png"),
 ("water-bottle",B+"hf_20260529_154752_2ef125b4-a470-4eed-867f-4d2353290ae5.png"),
 ("juice-can",B+"hf_20260529_154758_5f042968-8ee8-4b9c-8871-13dc6e616cfc.jpeg"),
 ("drink-cup",B+"hf_20260529_154804_e3acf4ee-ae5f-4ab1-953b-5ced4a1d517f.png"),
 ("milk-carton",B+"hf_20260529_154809_0dcf2921-2768-4584-a56d-e007387a16f0.png"),
 ("jam-jar",B+"hf_20260529_154817_acd29a9f-4ac8-4b27-983e-7de09c424d0d.png"),
 ("egg",B+"hf_20260529_154823_a6eb16cd-db69-4ad0-b4b4-d1a993745855.png"),
 ("crayon-box",B+"hf_20260529_154832_5b4bc3a0-a899-41ed-be1d-fbcb8987e4a7.png"),
 ("burger",B+"hf_20260529_154839_16d714a8-337e-47c6-9670-3e2aaee553f6.png"),
 ("ice-cream-cone",B+"hf_20260529_154855_24b2c517-08ee-4d58-b67a-105a54a3978a.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+url[-4:])
    if not fetch(url,tmp): print("!! FETCH FAILED",name,url,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:32s} {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",(6*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,6); 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\new_objects_check.png"); print("sheet ready")
