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

CHARS = Path(r"C:\allgifted\mathapi11v2\public\assets\math\chars"); SRC = CHARS/"source"; SRC.mkdir(exist_ok=True)
base = "https://d8j0ntlcm91z4.cloudfront.net/user_3ENYB9gUptp5V9uUGoiaDV631pi/"
TARGET = 120*1024

JOBS = {
 "shark":      ("e46f6ef2-d962-4a92-a0a0-b22beba59f94","hf_20260529_133637_e46f6ef2-d962-4a92-a0a0-b22beba59f94.png"),
 "panda":      ("c1c5eca9-402f-486f-9d1e-c863a65538ed","hf_20260529_133645_c1c5eca9-402f-486f-9d1e-c863a65538ed.png"),
 "chick":      ("fc71f81a-7bec-402d-893d-16011b98b3e2","hf_20260529_133653_fc71f81a-7bec-402d-893d-16011b98b3e2.png"),
 "duck":       ("b7891286-7fa7-449e-a2dc-233888d5a46b","hf_20260529_133700_b7891286-7fa7-449e-a2dc-233888d5a46b.png"),
 "dinosaur":   ("7bff585d-992b-4f31-a755-efcc6f126125","hf_20260529_133808_7bff585d-992b-4f31-a755-efcc6f126125.png"),
 "cat-generic":("5c9c5e60-7295-4e7f-bc5a-660148d63c42","hf_20260529_133814_5c9c5e60-7295-4e7f-bc5a-660148d63c42.png"),
 "tortoise":   ("4001605c-5837-4fbe-a7b0-809b040b28bf","hf_20260529_133837_4001605c-5837-4fbe-a7b0-809b040b28bf.png"),
}
def fetch(u,d):
    for _ in range(5):
        try: urllib.request.urlretrieve(u,d); return True
        except Exception: time.sleep(2)
    return False

added=[]
for name,(jid,fn) in JOBS.items():
    tmp=SRC/("_src_"+name+".png")
    if not fetch(base+fn,tmp): print("FETCH FAIL",name); continue
    cut=remove(Image.open(tmp).convert("RGBA"))   # transparent, NO badge
    png=SRC/f"ags-math-char-{name}.png"; cut.save(png,optimize=True); tmp.unlink()
    webp=CHARS/f"ags-math-char-{name}.webp"
    for q in (90,86,82,78):
        cut.save(webp,"WEBP",quality=q,lossless=False)
        if webp.stat().st_size<=TARGET: break
    kb=webp.stat().st_size/1024
    added.append((name,jid,round(kb,1),webp.name))
    print(f"{webp.name:34s} {kb:6.1f}KB (q={q})", flush=True)

# manifest: append the 7 animals
mf=CHARS/"ags_math_characters_manifest.json"; m=json.loads(mf.read_text(encoding="utf-8"))
existing={e["id"] for e in m["characters"]}
for name,jid,kb,fname in added:
    if name in existing: continue
    m["characters"].append({"id":name,"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("manifest now:",m["count"],"entries")

# contact sheet on grey
names=[f"ags-math-char-{n}.webp" for n in JOBS]
cell=240; cols=4; rows=2
cv=Image.new("RGB",(cols*cell,rows*cell),(120,120,120)); dr=ImageDraw.Draw(cv)
for i,n in enumerate(names):
    im=Image.open(CHARS/n).convert("RGBA"); im.thumbnail((cell-16,cell-28),Image.LANCZOS)
    r,c=divmod(i,cols); x,y=c*cell,r*cell
    cv.paste(im,(x+(cell-im.width)//2,y+24+(cell-28-im.height)//2),im)
    dr.rectangle([x,y,x+cell-1,y+20],fill=(20,20,20)); dr.text((x+3,y+5),n.replace("ags-math-char-","").replace(".webp",""),fill=(255,255,0))
cv.save(r"C:\allgifted\logo-reveal\animals_check.png"); print("contact sheet ready")
