"""Render a Julia or Newton wallpaper. Requires numpy and Pillow."""

import argparse

import numpy as np
from PIL import Image


def plane(width, height, span, focus=0.62):
    x = (np.arange(width) + 0.5 - width / 2) * span / width
    y = (np.arange(height) + 0.5 - height * focus) * span / width
    return (-y[:, None] + 1j * x[None, :]).ravel()


def julia(width, height):
    z = plane(width, height, 2.28)
    active = np.arange(z.size)
    smooth = np.zeros(z.size)
    c = -0.7269 + 0.1889j
    for step in range(300):
        z[active] = z[active] ** 2 + c
        radius = np.abs(z[active])
        escaped = radius > 256
        smooth[active[escaped]] = step + 1 - np.log2(np.log(radius[escaped]) / np.log(256))
        active = active[~escaped]
        if not active.size:
            break

    value = np.log1p(smooth)
    outside = smooth > 0
    tone = np.zeros_like(value)
    if np.any(outside):
        low, high = np.percentile(value[outside], [5, 99])
        if high > low:
            tone[outside] = np.clip((value[outside] - low) / (high - low), 0, 1)
    stops = [0, 0.36, 0.65, 0.82, 1]
    colors = np.array([[8, 16, 26], [20, 48, 70], [27, 120, 126], [108, 198, 175], [254, 225, 160]])
    return np.column_stack([np.interp(tone, stops, channel) for channel in colors.T])


def newton(width, height):
    z = plane(width, height, 2.65)
    colors = np.array([[22, 31, 53], [232, 159, 90], [204, 97, 79], [73, 159, 142], [108, 88, 155]])
    n = len(colors)
    roots = np.exp(2j * np.pi * np.arange(n) / n)
    rgb = np.tile([10, 17, 28], (z.size, 1)).astype(float)
    active = np.arange(z.size)
    for step in range(80):
        active = active[np.abs(z[active]) > 1e-9]  # Newton's step is undefined at zero.
        if not active.size:
            break
        current = z[active]
        z[active] = ((n - 1) * current + 1 / current ** (n - 1)) / n
        angle = np.angle(z[active])
        nearest = np.rint(angle * n / (2 * np.pi)).astype(int) % n
        settled = np.abs(z[active] - roots[nearest]) < 0.0005
        shade = max(0.18, 1 - step / 33)
        rgb[active[settled]] = colors[nearest[settled]] * shade
        active = active[~settled]
    return rgb


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("pattern", choices=["julia", "newton"])
    parser.add_argument("--width", type=int, default=1320)
    parser.add_argument("--height", type=int, default=2868)
    args = parser.parse_args()
    if args.width < 1 or args.height < 1:
        parser.error("width and height must be positive")
    render = {"julia": julia, "newton": newton}[args.pattern]
    pixels = render(args.width, args.height).reshape(args.height, args.width, 3)
    Image.fromarray(np.rint(pixels).astype(np.uint8)).save(f"{args.pattern}-wallpaper.png")


if __name__ == "__main__":
    main()
