import urllib.request, time, json
from rembg import remove
from PIL import Image
from pathlib import Path

CH = Path(r"C:\allgifted\mathapi11v2\public\assets\math\chars"); CHS=CH/"source"
OB = Path(r"C:\allgifted\mathapi11v2\public\assets\math\objects"); OBS=OB/"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
def proc(jid, fn, outdir, srcdir, name):
    tmp=srcdir/("_src_"+name+".png"); fetch(base+fn,tmp)
    cut=remove(Image.open(tmp).convert("RGBA")); cut.save(srcdir/f"{name}.png",optimize=True); tmp.unlink()
    webp=outdir/f"{name}.webp"
    for q in (90,86,82,78):
        cut.save(webp,"WEBP",quality=q,lossless=False)
        if webp.stat().st_size<=TARGET: break
    return jid, round(webp.stat().st_size/1024,1), webp.name

CHARS=[
 ("d6cf1d32","hf_20260529_145230_d6cf1d32-8cee-4c5e-8671-6d0caca1e51e.png","ags-math-char-child-girl"),
 ("7d39b320","hf_20260529_145238_7d39b320-bcae-426f-a1fb-42ed84f43f47.png","ags-math-char-girl-pose-wave"),
 ("d88ca2e8","hf_20260529_145247_d88ca2e8-bc1a-4308-bd3f-2258297c6973.png","ags-math-char-girl-pose-point"),
 ("e75f885f","hf_20260529_145251_e75f885f-c277-449c-bc68-04492740bdf5.png","ags-math-char-girl-pose-thumbsup"),
 ("e9fca41c","hf_20260529_145256_e9fca41c-0971-41e3-9381-9ccc02ddff16.png","ags-math-char-girl-pose-sit"),
 ("bd16a4c5","hf_20260529_145303_bd16a4c5-ce2c-4fd3-9855-dc5494b386f9.png","ags-math-char-girl-pose-jump"),
]
OBJS=[
 ("50b649a2","hf_20260529_145310_50b649a2-da42-4666-b081-e082a166427f.png","ags-math-obj-teddy-bear"),
 ("b890855f","hf_20260529_145316_b890855f-d170-4525-9c14-bcb12f517bce.png","ags-math-obj-rubiks-cube"),
 ("4cf43f44","hf_20260529_145322_4cf43f44-235c-4062-939e-6cbac5b2cb12.png","ags-math-obj-jetpack-bag"),
]
def add(mf_path, key, rows, cdnseg):
    m=json.loads(Path(mf_path).read_text(encoding="utf-8")); ex={e["id"] for e in m[key]}
    for jid,kb,fname in rows:
        cid=fname.replace(".webp","")
        if cid in ex:
            for e in m[key]:
                if e["id"]==cid: e["file_size_kb"]=kb; e["higgsfield_job_id"]=jid
            continue
        m[key].append({"id":cid,"filename":fname,"higgsfield_job_id":jid,"file_size_kb":kb,
            "cdn_url":f"https://math.allgifted.com/{cdnseg}/{fname}","format":"webp","background":"transparent","badge":"none","status":"approved"})
    m["count"]=len(m[key]); Path(mf_path).write_text(json.dumps(m,indent=2),encoding="utf-8"); return m["count"]

crows=[proc(j,f,CH,CHS,n) for j,f,n in CHARS]
orows=[proc(j,f,OB,OBS,n) for j,f,n in OBJS]
for j,kb,fn in crows+orows: print(f"{fn:36s} {kb:6.1f}KB",flush=True)
cc=add(CH/"ags_math_characters_manifest.json","characters",crows,"chars")
oc=add(OB/"ags_math_objects_manifest.json","objects",orows,"objects")
print("chars manifest:",cc,"  objects manifest:",oc)
