#!/usr/bin/env python3
"""
Generate a game icon or background PNG with Google Gemini's image model and save it
into a Sprites folder. Icons land on a solid white background (to match an icon set);
backgrounds are full-bleed. Output is always PNG (via Pillow).

Requires:  pip install google-genai pillow   and   GEMINI_API_KEY in the environment.

Examples:
  python gen_asset.py --type icon --name Trophy --prompt "a golden trophy cup"
  python gen_asset.py --type icon --name Clan --prompt "a shield crest" --ref ".../Coin.png"
  python gen_asset.py --type background --name ShopBG --prompt "tropical beach market at sunset" \
      --out ".../Resources/Sprites/Backgrounds" --size 1080x1920
"""
import argparse, os, sys, io

DEFAULT_OUT = r"D:/Unity/Jamaican Ludi/Assets/Resources/Sprites/Icons"


def _to_png_bytes(img):
    b = io.BytesIO(); img.save(b, "PNG"); return b.getvalue()


def cover_resize(img, W, H):
    from PIL import Image
    iw, ih = img.size
    scale = max(W / iw, H / ih)
    nw, nh = max(1, int(iw * scale)), max(1, int(ih * scale))
    img = img.resize((nw, nh), Image.LANCZOS)
    x, y = (nw - W) // 2, (nh - H) // 2
    return img.crop((x, y, x + W, y + H))


def main():
    ap = argparse.ArgumentParser(description="Generate a game icon/background PNG via Gemini.")
    ap.add_argument("--type", default="icon", choices=["icon", "background", "badge", "avatar"])
    ap.add_argument("--name", required=True, help="output filename without extension")
    ap.add_argument("--prompt", required=True, help="short description of the art")
    ap.add_argument("--out", default=DEFAULT_OUT, help="destination folder")
    ap.add_argument("--ref", default=None, help="optional reference image to match the style")
    ap.add_argument("--size", default=None, help="icon: N (square); background: WxH")
    ap.add_argument("--bg", default="transparent", choices=["transparent", "white"],
                    help="icon background: transparent cutout (default, needs rembg) or flat white")
    ap.add_argument("--frac", type=float, default=0.86,
                    help="icon: subject longest side as a fraction of the canvas (default 0.86)")
    ap.add_argument("--model", default=os.environ.get("GEMINI_IMAGE_MODEL", "gemini-2.5-flash-image"))
    a = ap.parse_args()

    key = os.environ.get("GEMINI_API_KEY") or os.environ.get("GOOGLE_API_KEY")
    if not key:
        sys.exit('ERROR: GEMINI_API_KEY not set. Windows: setx GEMINI_API_KEY "YOUR_KEY" then open a new terminal. '
                 'Get a key at https://aistudio.google.com/apikey')
    try:
        from google import genai
        from google.genai import types
    except ImportError:
        sys.exit("ERROR: missing package. Run: python -m pip install google-genai pillow")
    try:
        from PIL import Image
    except ImportError:
        sys.exit("ERROR: missing Pillow. Run: python -m pip install pillow")

    if a.type == "icon":
        style = (" -- a single centered mobile-game UI icon, bold and instantly readable, vibrant, "
                 "clean illustrated/2.5D style with subtle bevel and rim light, NO text or words, the subject "
                 "fully inside the frame with a small margin, on a SOLID PURE WHITE (#FFFFFF) background, square.")
        default_size = 512
    elif a.type == "badge":
        style = (" -- a single circular mobile-game UI badge/emblem that FILLS the square frame edge to edge, "
                 "ornate polished gold ring border, glossy 2.5D style with bevel and rim light, the emblem "
                 "subject centered inside the ring, NO text or words, NO white margin, transparent outside the disc.")
        default_size = 512
    elif a.type == "avatar":
        style = (" -- a friendly circular cartoon avatar that FILLS the square frame edge to edge, head and "
                 "shoulders, clean rounded shapes, smooth colored gradient circular background, polished "
                 "mobile-game style, NO text, NO white margin.")
        default_size = 512
    else:
        style = (" -- a full-bleed background illustration for a mobile game screen, richly detailed scene, "
                 "NO text and NO UI elements, with calmer space toward the center for UI overlay.")
        default_size = None

    prompt = a.prompt.strip().rstrip(".") + style

    client = genai.Client(api_key=key)
    contents = []
    if a.ref:
        if not os.path.exists(a.ref):
            sys.exit("ERROR: --ref not found: " + a.ref)
        contents.append(Image.open(a.ref))
        contents.append("Match the EXACT art style, palette, line weight, shading and finish of the reference image. " + prompt)
    else:
        contents.append(prompt)

    def gen(mods):
        return client.models.generate_content(
            model=a.model, contents=contents,
            config=types.GenerateContentConfig(response_modalities=mods))

    try:
        resp = gen(["IMAGE"])
    except Exception:
        resp = gen(["TEXT", "IMAGE"])  # some model/SDK combos require both

    img_bytes = None
    for cand in (resp.candidates or []):
        parts = getattr(getattr(cand, "content", None), "parts", None) or []
        for part in parts:
            inl = getattr(part, "inline_data", None)
            if inl and getattr(inl, "data", None):
                img_bytes = inl.data
                break
        if img_bytes:
            break
    if not img_bytes:
        sys.exit("ERROR: model returned no image. Try a different --model (e.g. gemini-2.0-flash-preview-image-generation) "
                 "or simplify the prompt. First 400 chars of response: " + str(resp)[:400])

    img = Image.open(io.BytesIO(img_bytes)).convert("RGBA")

    if a.type == "icon":
        size = int(a.size) if (a.size and "x" not in a.size.lower()) else default_size
        # Models put the subject on a solid bg even when asked for white. Isolate it
        # with rembg so the saved PNG has a real alpha channel (transparent cutout) and
        # a uniform footprint. Pass --bg white to keep the old flat-white behavior.
        if a.bg == "transparent":
            try:
                from rembg import remove
                cut = Image.open(io.BytesIO(remove(_to_png_bytes(img)))).convert("RGBA")
                if cut.getbbox():
                    img = cut
            except Exception as e:
                print("NOTE: rembg unavailable (" + str(e)[:60] + "); falling back to white bg.")
                a.bg = "white"
        bbox = img.getbbox()
        if bbox:
            img = img.crop(bbox)
        w, h = img.size
        scale = (a.frac * size) / max(w, h)
        nw, nh = max(1, round(w * scale)), max(1, round(h * scale))
        sub = img.resize((nw, nh), Image.LANCZOS)
        bgcol = (255, 255, 255, 255) if a.bg == "white" else (0, 0, 0, 0)
        canvas = Image.new("RGBA", (size, size), bgcol)
        canvas.paste(sub, ((size - nw) // 2, (size - nh) // 2), sub)
        img = canvas if a.bg == "transparent" else canvas.convert("RGB")
    elif a.type in ("badge", "avatar"):
        size = int(a.size) if (a.size and "x" not in a.size.lower()) else default_size
        w, h = img.size
        s = max(w, h)
        sq = Image.new("RGBA", (s, s), (0, 0, 0, 0))
        sq.paste(img, ((s - w) // 2, (s - h) // 2), img)
        img = sq.resize((size, size), Image.LANCZOS)
    else:
        if a.size and "x" in a.size.lower():
            W, H = [int(v) for v in a.size.lower().split("x")]
        else:
            W, H = 1080, 1920
        img = cover_resize(img.convert("RGB"), W, H)

    os.makedirs(a.out, exist_ok=True)
    path = os.path.join(a.out, a.name + ".png")
    img.save(path, "PNG")
    print("SAVED:", path, img.size)


if __name__ == "__main__":
    main()
