#!/usr/bin/env python3
"""Generate unique placeholder block sprites Tim can later replace."""
from __future__ import annotations

import math
from pathlib import Path

from PIL import Image, ImageDraw, ImageFilter

ROOT = Path(__file__).resolve().parents[1]
OUT = ROOT / "build" / "images"
SIZE = 64


def canvas(color=(0, 0, 0, 0)) -> Image.Image:
    return Image.new("RGBA", (SIZE, SIZE), color)


def shade(hex_color: str, factor: float) -> tuple[int, int, int, int]:
    h = hex_color.lstrip("#")
    r, g, b = int(h[0:2], 16), int(h[2:4], 16), int(h[4:6], 16)
    r = max(0, min(255, int(r * factor)))
    g = max(0, min(255, int(g * factor)))
    b = max(0, min(255, int(b * factor)))
    return (r, g, b, 255)


def disc(draw: ImageDraw.ImageDraw, cx, cy, r, fill, outline=None, width=2):
    box = [cx - r, cy - r, cx + r, cy + r]
    draw.ellipse(box, fill=fill, outline=outline, width=width if outline else 0)


def regular_polygon(cx, cy, r, n, rotation_deg=0):
    pts = []
    rot = math.radians(rotation_deg - 90)
    for i in range(n):
        a = rot + 2 * math.pi * i / n
        pts.append((cx + r * math.cos(a), cy + r * math.sin(a)))
    return pts


def star_points(cx, cy, r_out, r_in, n=5, rotation_deg=0):
    pts = []
    rot = math.radians(rotation_deg - 90)
    for i in range(n * 2):
        r = r_out if i % 2 == 0 else r_in
        a = rot + math.pi * i / n
        pts.append((cx + r * math.cos(a), cy + r * math.sin(a)))
    return pts


def bevel_shape(base: Image.Image) -> Image.Image:
    """Soft inner highlight and drop shadow, keeping alpha."""
    alpha = base.getchannel("A")
    shadow = Image.new("RGBA", base.size, (0, 0, 0, 0))
    sh = Image.new("L", base.size, 0)
    sh.paste(alpha, (2, 3))
    sh = sh.filter(ImageFilter.GaussianBlur(2))
    shadow.putalpha(sh.point(lambda v: int(v * 0.45)))
    out = Image.alpha_composite(shadow, base)
    # top-left highlight
    hi = Image.new("RGBA", base.size, (0, 0, 0, 0))
    hid = ImageDraw.Draw(hi)
    hid.ellipse((8, 6, 30, 24), fill=(255, 255, 255, 70))
    hi.putalpha(ImageChops.multiply(hi.getchannel("A"), alpha))
    out = Image.alpha_composite(out, hi)
    return out


from PIL import ImageChops  # after use in bevel — move to top conceptually, fine at runtime


def draw_block(shape: str, color: str) -> Image.Image:
    img = canvas()
    body = canvas()
    d = ImageDraw.Draw(body)
    cx = cy = SIZE / 2
    fill = shade(color, 1.0)
    dark = shade(color, 0.55)
    light = shade(color, 1.25)
    if shape == "triangle":
        pts = regular_polygon(cx, cy + 3, 26, 3, 0)
        d.polygon(pts, fill=fill, outline=dark)
    elif shape == "circle":
        disc(d, cx, cy, 25, fill, dark, 3)
        disc(d, cx - 6, cy - 7, 8, (255, 255, 255, 70), None)
    elif shape == "square":
        r = 12
        d.rounded_rectangle((10, 10, 54, 54), radius=r, fill=fill, outline=dark, width=3)
    elif shape == "diamond":
        pts = regular_polygon(cx, cy, 27, 4, 0)
        d.polygon(pts, fill=fill, outline=dark)
    elif shape == "star":
        pts = star_points(cx, cy, 28, 13, 5, 0)
        d.polygon(pts, fill=fill, outline=dark)
    else:
        d.rounded_rectangle((8, 8, 56, 56), 10, fill=fill, outline=dark, width=3)
    # inner edge
    if shape != "circle":
        inner = body.filter(ImageFilter.SMOOTH_MORE)
        body = inner
    return bevel_shape(body)


def draw_gray(locked=False) -> Image.Image:
    img = canvas()
    d = ImageDraw.Draw(img)
    fill = (48, 50, 56, 255) if not locked else (28, 28, 32, 255)
    dark = (20, 20, 24, 255)
    d.rounded_rectangle((8, 8, 56, 56), 10, fill=fill, outline=dark, width=3)
    # rivets
    for x, y in ((16, 16), (48, 16), (16, 48), (48, 48)):
        disc(d, x, y, 3, (70, 72, 78, 255) if not locked else (16, 16, 18, 255))
    if locked:
        # a muted cross
        d.line((20, 20, 44, 44), fill=(90, 40, 40, 220), width=5)
        d.line((44, 20, 20, 44), fill=(90, 40, 40, 220), width=5)
    else:
        # engine nozzle hint at the bottom
        d.rounded_rectangle((24, 50, 40, 58), 3, fill=(24, 24, 28, 255))
    return bevel_shape(img)


def draw_flame_strip() -> Image.Image:
    frames = 4
    strip = Image.new("RGBA", (SIZE * frames, SIZE), (0, 0, 0, 0))
    for i in range(frames):
        fr = canvas()
        d = ImageDraw.Draw(fr)
        # Flicker: length and lean change per frame
        lean = (-1, 1, 0, -0.5)[i] * 4
        length = (26, 30, 22, 28)[i]
        cx = SIZE / 2 + lean
        top = 8
        bot = 8 + length
        # outer, mid, core
        pts_outer = [(cx - 14, top), (cx + 14, top), (cx + lean * 0.3, bot)]
        pts_mid = [(cx - 9, top + 2), (cx + 9, top + 2), (cx + lean * 0.2, bot - 4)]
        pts_core = [(cx - 4, top + 3), (cx + 4, top + 3), (cx, bot - 10)]
        d.polygon(pts_outer, fill=(255, 110, 20, 230))
        d.polygon(pts_mid, fill=(255, 180, 40, 240))
        d.polygon(pts_core, fill=(255, 250, 200, 255))
        fr = fr.filter(ImageFilter.GaussianBlur(0.6))
        strip.paste(fr, (i * SIZE, 0), fr)
    return strip


def draw_cell() -> Image.Image:
    img = Image.new("RGBA", (SIZE, SIZE), (18, 22, 36, 255))
    d = ImageDraw.Draw(img)
    d.rectangle((0, 0, 63, 63), outline=(36, 44, 70, 255), width=1)
    d.rectangle((1, 1, 62, 62), outline=(12, 14, 24, 200), width=1)
    return img


def draw_pixel() -> Image.Image:
    return Image.new("RGBA", (1, 1), (0, 0, 0, 0))


def main():
    OUT.mkdir(parents=True, exist_ok=True)
    blocks = {
        "block-ember.png": ("triangle", "#e85d3a"),
        "block-aqua.png": ("circle", "#3db8e8"),
        "block-leaf.png": ("square", "#4cbf4c"),
        "block-sun.png": ("diamond", "#f0c53a"),
        "block-orchid.png": ("star", "#c45ad4"),
    }
    for name, (shape, color) in blocks.items():
        draw_block(shape, color).save(OUT / name, "PNG")
        print("wrote", name)
    draw_gray(False).save(OUT / "block-gray.png", "PNG")
    print("wrote block-gray.png")
    draw_gray(True).save(OUT / "block-locked.png", "PNG")
    print("wrote block-locked.png")
    draw_flame_strip().save(OUT / "flame.png", "PNG")
    print("wrote flame.png")
    draw_cell().save(OUT / "cell.png", "PNG")
    print("wrote cell.png")
    draw_pixel().save(OUT / "pixel.png", "PNG")
    print("wrote pixel.png")


if __name__ == "__main__":
    main()
