"""
A Python script to draw a fish scale pattern with horizontal rows of
overlapping circles.
"""

from collections.abc import Iterator
import colorsys
import math
import random
import sys


def random_colours_like(hex_colour: str) -> Iterator[tuple[int, int, int]]:
    """
    Given a hex colour as a string, generate an infinite sequence
    of colours which vary only in brightness.
    """
    r = int(hex_colour[1:3], 16)
    g = int(hex_colour[3:5], 16)
    b = int(hex_colour[5:7], 16)

    hue, lightness, saturation = colorsys.rgb_to_hls(r / 255, g / 255, b / 255)

    min_lightness = lightness * 7.5 / 8
    max_lightness = lightness * 8 / 7

    if hex_colour == "#9dc0cb":
        min_lightness = lightness * 7 / 8
        max_lightness = lightness * 8 / 7

    if hex_colour == "#007b92":
        min_lightness = lightness * 6 / 8
        max_lightness = lightness * 9 / 7

    lightness_diff = max_lightness - min_lightness

    while True:
        r, g, b = colorsys.hls_to_rgb(
            hue, min_lightness + lightness_diff * random.random(), saturation
        )

        yield round(r * 255), round(g * 255), round(b * 255)


def generate_circle_centres(
    width: int, height: int, x_spacing: int, y_spacing: int
) -> Iterator[tuple[int, int]]:
    """
    Generate the centres of circles arranged in a triangular pattern.
    """
    y_min = - 10
    y_max = height + 10

    for rowno, y in enumerate(range(y_min, y_max, y_spacing)):
        for x in range(width + x_spacing, -x_spacing, -x_spacing):
            if rowno % 2 == 0:
                yield (x + x_spacing / 2, y)
            else:
                yield (x, y)


if __name__ == "__main__":
    try:
        hex_colour = sys.argv[1]
    except IndexError:
        sys.exit(f"Usage: {__file__} HEX_COLOUR")

    import random
    from PIL import Image, ImageDraw

    width = 500
    height = 500
    radius = 50

    x_spacing = radius * 2
    y_spacing = radius

    r = int(hex_colour[1:3], 16)
    g = int(hex_colour[3:5], 16)
    b = int(hex_colour[5:7], 16)

    hue, lightness, saturation = colorsys.rgb_to_hls(r / 255, g / 255, b / 255)

    r, g, b = colorsys.hls_to_rgb(hue, lightness * 6.5 / 8, saturation)
    r, g, b = round(r * 255), round(g * 255), round(b * 255)

    im = Image.new("RGBA", size=(width, height))
    draw = ImageDraw.Draw(im)

    centres = generate_circle_centres(width, height, x_spacing, y_spacing)
    colours = random_colours_like(hex_colour)

    for (x, y), colour in zip(centres, colours):
        draw.ellipse(
            [(x - radius, y - radius), (x + radius, y + radius)], fill=(r, g, b)
        )
        draw.ellipse(
            [
                (x - radius * 0.95, y - radius * 0.95),
                (x + radius * 0.95, y + radius * 0.95),
            ],
            fill=colour,
        )

    im.save("circles.png")
