import random
import math
import numpy as np
from PIL import Image, ImageDraw

SEED = 4711
random.seed(SEED)
np.random.seed(SEED)

SIZE = 1200

# Flexoki palette — swatches used exactly as given.
# Wall: paper.  Gray wash: base-400.  Black ink: black.
PAPER = (255, 252, 240)
BASE_100 = (230, 228, 217)
BASE_200 = (206, 205, 195)
BASE_300 = (183, 181, 172)
BASE_400 = (159, 157, 150)
BASE_500 = (135, 133, 128)
BASE_600 = (111, 110, 105)
BASE_700 = (87, 86, 83)
BASE_800 = (64, 62, 60)
BASE_850 = (52, 51, 49)
BASE_900 = (40, 38, 36)
BASE_950 = (28, 27, 26)
BLACK = (16, 15, 15)

# Neutral ramp for the ink diffusion: black at the drop,
# base-400 (the gray wash) where the spread ends.  Nine
# discrete steps — no interpolation between swatches.
DIFFUSION_RAMP = np.array([
    BLACK,        # 0 — the drop, darkest
    BASE_950,
    BASE_900,
    BASE_850,
    BASE_800,
    BASE_700,
    BASE_600,
    BASE_500,
    BASE_400,     # 8 — the gray wash, where the spread ends
], dtype=np.uint8)

WASH = BASE_400

img = Image.new('RGB', (SIZE, SIZE), PAPER)
draw = ImageDraw.Draw(img)


def place_blocks(n, margin=70, max_tries=400):
    """Seven blocks at chance places and sizes, kept from
    overlapping so each wash reads as its own block."""
    blocks = []
    for _ in range(n):
        placed = False
        for _try in range(max_tries):
            w = int(random.uniform(200, 430))
            h = int(random.uniform(200, 400))
            x = int(random.uniform(margin, SIZE - margin - w))
            y = int(random.uniform(margin, SIZE - margin - h))
            box = (x, y, x + w, y + h)
            ok = True
            for (bx, by, bx2, by2) in blocks:
                if not (box[2] < bx - 25 or box[0] > bx2 + 25 or
                        box[3] < by - 25 or box[1] > by2 + 25):
                    ok = False
                    break
            if ok:
                blocks.append(box)
                placed = True
                break
        if not placed:
            # give up on separation; place anywhere
            w = int(random.uniform(180, 380))
            h = int(random.uniform(180, 360))
            x = int(random.uniform(margin, SIZE - margin - w))
            y = int(random.uniform(margin, SIZE - margin - h))
            blocks.append((x, y, x + w, y + h))
    return blocks


blocks = place_blocks(7)

for (bx, by, bx2, by2) in blocks:
    bw = bx2 - bx
    bh = by2 - by

    # --- The gray ink wash, too dry to drip ---
    draw.rectangle([bx, by, bx2, by2], fill=WASH)

    # --- One drop of black ink at a chance point while the block is wet ---
    # Biased to the upper half so the spread has room to reach the lower edge.
    dx = bx + bw * random.uniform(0.28, 0.72)
    dy = by + bh * random.uniform(0.22, 0.52)

    # The black spreads through the gray until it reaches the block's
    # lower edge — that distance is the spread radius.
    max_radius = (by2 - dy)

    # --- The spread, as a stepped radial diffusion inside the block ---
    yy, xx = np.meshgrid(
        np.arange(by, by2), np.arange(bx, bx2), indexing="ij"
    )
    dist = np.sqrt((xx - dx) ** 2 + (yy - dy) ** 2)

    # Map distance to one of the nine ramp steps.  dist = 0 is the
    # drop (black); dist >= max_radius is the gray wash untouched.
    norm = dist / max_radius
    idx = np.clip((norm * (len(DIFFUSION_RAMP) - 1)).astype(int), 0,
                  len(DIFFUSION_RAMP) - 1)
    block_rgb = DIFFUSION_RAMP[idx]

    # A little chance in the edge of the spread, so the ring where the
    # black meets the gray is not a perfect circle.
    edge_noise = np.random.rand(bh, bw)
    ring = (norm > 0.78) & (norm < 1.0)
    scatter = ring & (edge_noise < 0.35)
    idx2 = idx.copy()
    idx2[scatter] = len(DIFFUSION_RAMP) - 1  # back to the plain wash
    block_rgb = DIFFUSION_RAMP[idx2]

    block_img = Image.fromarray(block_rgb, "RGB")
    img.paste(block_img, (bx, by))

    # --- Where the spread reaches the block's lower edge, it drips ---
    # The drip leaves from the foot of the spread, straight down.
    drip_x = dx
    drip_top = by2
    drip_len = random.uniform(90, 260)
    drip_w = 4
    draw.rectangle(
        [drip_x - drip_w / 2, drip_top, drip_x + drip_w / 2,
         drip_top + drip_len],
        fill=BLACK,
    )
    # The bead at the end of the drip
    r_bead = drip_w * 1.6
    draw.ellipse(
        [drip_x - r_bead, drip_top + drip_len - r_bead,
         drip_x + r_bead, drip_top + drip_len + r_bead],
        fill=BLACK,
    )

img.save("render-1.png")
