"""
Asset preparation for Saudi eLeague Pac-Man.
Run once: `python prep_assets.py`
Turtle only supports GIF for custom shapes, so we convert the source
mascot PNG and generate themed lightning-bolt sprites via Pillow.
"""
import os
from PIL import Image, ImageDraw

HERE = os.path.dirname(os.path.abspath(__file__))
OUT = os.path.join(HERE, "assets")
os.makedirs(OUT, exist_ok=True)

SRC_DIR = os.path.join(os.path.expanduser("~"), "Downloads", "Assets ", "Mascot")
MASCOT_SRC = os.path.join(SRC_DIR, "A4 - 3.png")
BANNER_SRC = os.path.join(SRC_DIR, "A4 - 2.png")

BG = (10, 10, 26)           # #0A0A1A
ACCENT_CYAN = (0, 212, 255) # #00D4FF
ACCENT_GREEN = (0, 255, 135)
GOLD = (255, 215, 0)


def flatten_to_bg(img, bg=BG):
    "Composite RGBA image onto the game background so GIF transparency looks clean."
    if img.mode != "RGBA":
        img = img.convert("RGBA")
    out = Image.new("RGB", img.size, bg)
    out.paste(img, mask=img.split()[3])
    return out


def save_gif(img, name):
    path = os.path.join(OUT, name)
    img.save(path, "GIF")
    print("wrote", path)
    return path


def make_player():
    "Crop mascot to its bounding box and resize to sprite size."
    src = Image.open(MASCOT_SRC).convert("RGBA")
    bbox = src.getbbox()
    cropped = src.crop(bbox)
    w, h = cropped.size
    side = max(w, h)
    square = Image.new("RGBA", (side, side), (0, 0, 0, 0))
    square.paste(cropped, ((side - w) // 2, (side - h) // 2))
    sprite = square.resize((46, 46), Image.LANCZOS)
    save_gif(flatten_to_bg(sprite), "player.gif")


def make_lightning(size, color, name):
    "Draw a lightning-bolt glyph on a transparent square, then flatten to bg."
    scale = 4
    canvas = Image.new("RGBA", (size * scale, size * scale), (0, 0, 0, 0))
    d = ImageDraw.Draw(canvas)
    s = size * scale
    pts = [
        (s * 0.55, s * 0.05),
        (s * 0.20, s * 0.55),
        (s * 0.45, s * 0.55),
        (s * 0.35, s * 0.95),
        (s * 0.80, s * 0.40),
        (s * 0.52, s * 0.40),
        (s * 0.68, s * 0.05),
    ]
    d.polygon(pts, fill=color + (255,), outline=(255, 255, 255, 255))
    sprite = canvas.resize((size, size), Image.LANCZOS)
    save_gif(flatten_to_bg(sprite), name)


def make_banner():
    "Resize the Saudi eLeague banner for use as an in-game watermark."
    src = Image.open(BANNER_SRC).convert("RGBA")
    w, h = src.size
    target_h = 70
    target_w = int(w * target_h / h)
    sprite = src.resize((target_w, target_h), Image.LANCZOS)
    save_gif(flatten_to_bg(sprite), "banner.gif")


if __name__ == "__main__":
    make_player()
    make_lightning(14, ACCENT_CYAN, "pellet.gif")
    make_lightning(26, ACCENT_GREEN, "power.gif")
    make_banner()
    print("done.")
