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

CHARS = Path(r"C:\allgifted\mathapi11v2\public\assets\math\chars")
LOGO  = Path(r"C:\allgifted\logo-reveal")
SRC   = CHARS / "source"; SRC.mkdir(exist_ok=True)
base  = "https://d8j0ntlcm91z4.cloudfront.net/user_3ENYB9gUptp5V9uUGoiaDV631pi/"
badge_src = Image.open(CHARS / "ag_badge.png").convert("RGBA")

def add_badge(rgba, frac=0.07, pad=14, opacity=0.55):
    tw = int(rgba.width * frac)
    b = badge_src.resize((tw, int(badge_src.height * tw / badge_src.width)), Image.LANCZOS)
    r, g, bl, a = b.split(); a = a.point(lambda v: int(v * opacity))
    b = Image.merge("RGBA", (r, g, bl, a))
    layer = Image.new("RGBA", rgba.size, (0,0,0,0))
    layer.paste(b, (rgba.width - b.width - pad, rgba.height - b.height - pad))
    return Image.alpha_composite(rgba, layer)

# --- Mei (approved slim mother bear, job f874e269) -> chars ---
tmp = CHARS / "_mei_src.png"
for i in range(5):
    try: urllib.request.urlretrieve(base + "hf_20260529_090147_f874e269-d58d-4b3e-862e-f00b06aaefbd.png", tmp); break
    except Exception: time.sleep(2)
cut = add_badge(remove(Image.open(tmp).convert("RGBA")))
cut.save(CHARS / "ags-math-char-mei.png", optimize=True); tmp.unlink()
print(f"mei added: {(CHARS/'ags-math-char-mei.png').stat().st_size/1024:.1f}KB", flush=True)

# --- Lucky v7 (v5 body + single fang) -> chars (overwrite the hand-edited v5) ---
cutL = add_badge(remove(Image.open(LOGO / "lucky_v7.png").convert("RGBA")))
cutL.save(CHARS / "ags-math-char-lucky.png", optimize=True)
print(f"lucky v7 set: {(CHARS/'ags-math-char-lucky.png').stat().st_size/1024:.1f}KB", flush=True)

# --- WebP convert all chars; move PNG sources to /source ---
for f in sorted(CHARS.glob("ags-math-char-*.png")):
    img = Image.open(f).convert("RGBA")
    webp = f.with_suffix(".webp")
    img.save(webp, "WEBP", quality=90, lossless=False)
    shutil.move(str(f), str(SRC / f.name))
    print(f"{f.name:30s} -> {webp.name:31s} {webp.stat().st_size//1024}KB (png->source/)", flush=True)
print("DONE", flush=True)
