#!/usr/bin/env python3
"""Unique placeholder block images for each planet color.

Tim can replace any of these PNGs in build/images/. Filenames stay stable.
Run from the repo root: python3 scripts/gen_planet_blocks.py
"""
from __future__ import annotations

import json
import math
from pathlib import Path

from PIL import Image, ImageDraw, ImageFilter, ImageChops

ROOT = Path(__file__).resolve().parents[1]
CATALOG = ROOT / 'server' / 'lib' / 'planets.json'
OUT = ROOT / 'build' / 'images'
SIZE = 64
SCALE = 4  # supersample
SS = SIZE * SCALE


def hex_rgb(h):
    h = h.lstrip('#')
    return tuple(int(h[i:i + 2], 16) for i in (0, 2, 4))


def lighten(rgb, f=0.35):
    return tuple(min(255, int(c + (255 - c) * f)) for c in rgb)


def darken(rgb, f=0.28):
    return tuple(max(0, int(c * (1 - f))) for c in rgb)


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


def star_pts(cx, cy, r, n=5, inner=0.42, rot=-math.pi / 2):
    pts = []
    for i in range(n * 2):
        a = rot + i * math.pi / n
        rr = r if i % 2 == 0 else r * inner
        pts.append((cx + rr * math.cos(a), cy + rr * math.sin(a)))
    return pts


def draw_shape(draw, shape, cx, cy, r, fill, outline, width):
    shape = shape.lower()
    if shape == 'circle':
        box = [cx - r, cy - r, cx + r, cy + r]
        draw.ellipse(box, fill=fill, outline=outline, width=width)
    elif shape == 'square':
        s = r * 0.86
        box = [cx - s, cy - s, cx + s, cy + s]
        draw.rounded_rectangle(box, radius=r * 0.12, fill=fill, outline=outline, width=width)
    elif shape == 'triangle':
        pts = regular_poly(cx, cy + r * 0.08, r * 1.08, 3, -math.pi / 2)
        draw.polygon(pts, fill=fill, outline=outline, width=width)
    elif shape == 'diamond':
        pts = regular_poly(cx, cy, r * 1.05, 4, 0)
        draw.polygon(pts, fill=fill, outline=outline, width=width)
    elif shape == 'star':
        draw.polygon(star_pts(cx, cy, r * 1.12), fill=fill, outline=outline, width=width)
    elif shape == 'hexagon':
        draw.polygon(regular_poly(cx, cy, r * 1.05, 6, 0), fill=fill, outline=outline, width=width)
    elif shape == 'pentagon':
        draw.polygon(regular_poly(cx, cy, r * 1.08, 5), fill=fill, outline=outline, width=width)
    elif shape == 'teardrop':
        # circle + top point
        pts = []
        for i in range(24):
            a = math.pi * 0.22 + i * (2 * math.pi * 0.78) / 23
            pts.append((cx + r * 0.85 * math.cos(a), cy + r * 0.25 + r * 0.85 * math.sin(a)))
        pts.insert(0, (cx, cy - r * 1.1))
        draw.polygon(pts, fill=fill, outline=outline, width=width)
    elif shape == 'crescent':
        # Draw a moon by punching a circle out of another.
        # ImageDraw can't punch; caller uses a mask. Fallback: thick arc-like poly.
        outer = []
        inner = []
        for i in range(22):
            a = -math.pi * 0.7 + i * (1.4 * math.pi) / 21
            outer.append((cx + r * math.cos(a) - r * 0.08, cy + r * math.sin(a)))
        ox, oy = cx + r * 0.42, cy - r * 0.05
        for i in range(18, -1, -1):
            a = -math.pi * 0.65 + i * (1.3 * math.pi) / 18
            inner.append((ox + r * 0.72 * math.cos(a), oy + r * 0.72 * math.sin(a)))
        draw.polygon(outer + inner, fill=fill, outline=outline, width=width)
    elif shape == 'plus':
        t = r * 0.38
        pts = [
            (cx - t, cy - r), (cx + t, cy - r), (cx + t, cy - t),
            (cx + r, cy - t), (cx + r, cy + t), (cx + t, cy + t),
            (cx + t, cy + r), (cx - t, cy + r), (cx - t, cy + t),
            (cx - r, cy + t), (cx - r, cy - t), (cx - t, cy - t),
        ]
        draw.polygon(pts, fill=fill, outline=outline, width=width)
    elif shape == 'gem':
        pts = [
            (cx, cy - r), (cx + r * 0.72, cy - r * 0.15),
            (cx + r * 0.5, cy + r * 0.95), (cx - r * 0.5, cy + r * 0.95),
            (cx - r * 0.72, cy - r * 0.15),
        ]
        draw.polygon(pts, fill=fill, outline=outline, width=width)
    elif shape == 'arrow':
        pts = [
            (cx, cy - r * 1.1), (cx + r * 0.85, cy + r * 0.05),
            (cx + r * 0.28, cy + r * 0.05), (cx + r * 0.28, cy + r),
            (cx - r * 0.28, cy + r), (cx - r * 0.28, cy + r * 0.05),
            (cx - r * 0.85, cy + r * 0.05),
        ]
        draw.polygon(pts, fill=fill, outline=outline, width=width)
    else:
        draw.ellipse([cx - r, cy - r, cx + r, cy + r], fill=fill, outline=outline, width=width)


def render_block(hex_color, shape):
    rgb = hex_rgb(hex_color)
    hi = lighten(rgb, 0.42)
    lo = darken(rgb, 0.32)
    img = Image.new('RGBA', (SS, SS), (0, 0, 0, 0))
    draw = ImageDraw.Draw(img)
    cx = cy = SS / 2
    r = SS * 0.36
    # drop shadow
    shadow = Image.new('RGBA', (SS, SS), (0, 0, 0, 0))
    sd = ImageDraw.Draw(shadow)
    draw_shape(sd, shape, cx + SCALE * 1.2, cy + SCALE * 1.6, r, (0, 0, 0, 90), None, 0)
    shadow = shadow.filter(ImageFilter.GaussianBlur(radius=SCALE * 1.1))
    img = Image.alpha_composite(img, shadow)
    draw = ImageDraw.Draw(img)
    # body
    draw_shape(draw, shape, cx, cy, r, rgb + (255,), lo + (255,), max(2, SCALE))
    # highlight (smaller, offset, semi)
    hi_layer = Image.new('RGBA', (SS, SS), (0, 0, 0, 0))
    hd = ImageDraw.Draw(hi_layer)
    draw_shape(hd, shape, cx - r * 0.06, cy - r * 0.10, r * 0.55, hi + (110,), None, 0)
    # clip highlight to the body roughly by multiplying alpha later is hard;
    # a soft blob is fine for a placeholder.
    hi_layer = hi_layer.filter(ImageFilter.GaussianBlur(radius=SCALE * 0.6))
    img = Image.alpha_composite(img, hi_layer)
    out = img.resize((SIZE, SIZE), Image.Resampling.LANCZOS)
    return out


def main():
    data = json.loads(CATALOG.read_text())
    OUT.mkdir(parents=True, exist_ok=True)
    written = []
    seen = set()
    for planet in data['planets']:
        shapes = [c['shape'] for c in planet['colors']]
        if len(set(shapes)) != 5:
            raise SystemExit(f'{planet["id"]} does not have 5 unique shapes')
        for color in planet['colors']:
            path = ROOT / 'build' / color['image']
            if path.name in seen:
                raise SystemExit(f'duplicate filename {path}')
            seen.add(path.name)
            img = render_block(color['hex'], color['shape'])
            img.save(path, 'PNG', optimize=True)
            written.append(path.relative_to(ROOT))
    print(f'wrote {len(written)} placeholders to {OUT}')
    for p in written:
        print(' ', p)


if __name__ == '__main__':
    main()
