"""障子 / Shoji — recursive rectangle subdivision."""
import numpy as np
from PIL import Image, ImageDraw
from _common import W, H, C, rgb, paper, cli


def render(seed):
    rng = np.random.default_rng(seed)
    bg, cols, line = C["kinari"], [C["shu"], C["ai"], C["yamabuki"]], C["sumi"]
    img = Image.new("RGB", (W, H), rgb(bg)); d = ImageDraw.Draw(img)

    def split(x0, y0, x1, y1, depth):
        if depth > 6 or (x1 - x0) * (y1 - y0) < 90000 or (depth > 2 and rng.random() < 0.18):
            if rng.random() < 0.22:
                d.rectangle([x0, y0, x1, y1], fill=rgb(cols[rng.integers(len(cols))]))
            d.rectangle([x0, y0, x1, y1], outline=rgb(line), width=10)
            return
        # cut the long side somewhere between 30% and 70%
        if (x1 - x0) > (y1 - y0):
            m = x0 + (x1 - x0) * rng.uniform(0.3, 0.7); split(x0, y0, m, y1, depth + 1); split(m, y0, x1, y1, depth + 1)
        else:
            m = y0 + (y1 - y0) * rng.uniform(0.3, 0.7); split(x0, y0, x1, m, depth + 1); split(x0, m, x1, y1, depth + 1)

    split(80, 80, W - 80, H - 80, 0)
    return paper(img, rng)


SEED = 61

if __name__ == "__main__":
    cli(render, SEED)
