"""The Edge Dries Dark - a digital interpretation of today's wall drawing instruction,
drawn by program.

Instruction (quoted in full):
"Brush clean water on the wall in one broad patch, a third of the wall, off
center. While wet, rule one India ink line from corner to corner. On dry wall
it stays a hairline; where it crosses the patch it bleeds out toward the
patch's edges and dries dark there."

This program is a digital interpretation: it draws pixels that read as water
and ink on a wall. It does not simulate physical fluid behavior; every effect
below is a construction, described honestly in statement.md.

One seeded draw (seed 14) fixes every open choice:
  - which diagonal is ruled (corner to corner),
  - the patch's off-center direction and distance,
  - the patch's irregular brushed outline (radial harmonic wobble),
  - the brushing direction and its bristle streaking,
  - the wobble of the bleed front.

Definite parts, by construction:
  - one broad patch, scaled to one third of the wall's area (within 0.1%),
  - its centroid placed off the wall's center,
  - one straight line, ruled from one corner of the wall to the opposite,
  - on dry wall the line is drawn as an unbroken hairline,
  - inside the patch the hairline's ink is instead spread toward the patch's
    own edges, faint near the line and gathering darkest at the patch's
    boundary; nothing is drawn outside the patch except the hairline.

Render: render-1.png, 2000 x 2000 px.
"""

import numpy as np
from PIL import Image
from scipy.ndimage import distance_transform_edt, gaussian_filter

SIZE = 2000
SEED = 14
rng = np.random.default_rng(SEED)

PAPER = np.array([244.0, 240.0, 231.0])   # dry wall
WET_TINT = np.array([238.0, 237.0, 232.0])  # clean water on the wall: barely darker
INK = np.array([26.0, 26.0, 30.0])        # India ink

# --- the patch: one broad brushed shape, irregular outline -------------------
diag_choice = int(rng.integers(0, 2))  # 0: top-left to bottom-right, 1: top-right to bottom-left
off_angle = rng.uniform(0, 2 * np.pi)
off_dist = rng.uniform(0.10, 0.16) * SIZE          # off center, by chance
cx = SIZE / 2 + off_dist * np.cos(off_angle)
cy = SIZE / 2 + off_dist * np.sin(off_angle)

elong = rng.uniform(1.15, 1.45)                     # broad: longer than tall
elong_angle = rng.uniform(0, np.pi)                 # brushing direction
n_harm = int(rng.integers(4, 7))
harm_k = rng.integers(2, 9, size=n_harm)
harm_a = rng.uniform(0.03, 0.12, size=n_harm)
harm_a[0] = rng.uniform(0.08, 0.14)
harm_p = rng.uniform(0, 2 * np.pi, size=n_harm)
ragged_k = int(rng.integers(24, 40))                # fine brushed raggedness
ragged_a = rng.uniform(0.008, 0.016)
ragged_p = rng.uniform(0, 2 * np.pi)


def radius(theta):
    r = np.ones_like(theta)
    for k, a, p in zip(harm_k, harm_a, harm_p):
        r = r + a * np.cos(k * theta + p)
    r = r + ragged_a * np.cos(ragged_k * theta + ragged_p)
    return r


# outline as a polar polygon around the patch center, elongated along the brush
R0 = np.sqrt((SIZE * SIZE / 3.0) / np.pi)  # pixel base radius for a third of the wall
theta = np.linspace(0, 2 * np.pi, 4000, endpoint=False)
r = radius(theta)
ex = r * np.cos(theta) * elong
ey = r * np.sin(theta) / elong
rx = (ex * np.cos(elong_angle) - ey * np.sin(elong_angle)) * R0
ry = (ex * np.sin(elong_angle) + ey * np.cos(elong_angle)) * R0

# rasterize the outline supersampled, then scale to exactly a third of the wall
SS = 2
target_area = SIZE * SIZE / 3.0
scale = 1.0
for _ in range(40):
    img = Image.new("L", (SIZE * SS, SIZE * SS), 0)
    from PIL import ImageDraw

    d = ImageDraw.Draw(img)
    d.polygon(list(zip((cx + rx * scale) * SS, (cy + ry * scale) * SS)), fill=255)
    m = np.asarray(img.resize((SIZE, SIZE), Image.LANCZOS), dtype=float) / 255.0
    area = float((m > 0.5).sum())
    if abs(area - target_area) / target_area < 0.001:
        break
    scale *= np.sqrt(target_area / area)

# keep the whole patch on the wall: shift it back if the draw pushes an edge off
ys, xs = np.where(m > 0.5)
pad = 30
dx = min(0, xs.min() - pad) + max(0, xs.max() - (SIZE - pad))
dy = min(0, ys.min() - pad) + max(0, ys.max() - (SIZE - pad))
m = np.roll(m, (-int(np.round(dy)), -int(np.round(dx))), axis=(0, 1))
cy -= dy
cx -= dx
mask = m > 0.5
patch_area_frac = float(mask.sum()) / (SIZE * SIZE)

# bristle streaks: smooth noise stretched along the brushing direction
noise = rng.random((SIZE // 4, SIZE // 4))
streak = np.asarray(Image.fromarray((noise * 255).astype(np.uint8)).resize(
    (SIZE, SIZE), Image.BICUBIC), dtype=float) / 255.0
streak = gaussian_filter(streak, sigma=(2.0, 22.0))
# rotate the streak field so streaks run along the brush direction
streak_img = Image.fromarray((streak * 255).astype(np.uint8)).rotate(
    -np.degrees(elong_angle), resample=Image.BICUBIC, center=(cx, cy))
streak = np.asarray(streak_img, dtype=float) / 255.0
streak = streak - streak.mean()  # kept subtle below

# --- the ruled line: corner to corner ----------------------------------------
yy, xx = np.mgrid[0:SIZE, 0:SIZE].astype(float)
if diag_choice == 0:
    perp = (xx - yy) / np.sqrt(2.0)
    x0, y0, x1, y1 = 0, 0, SIZE, SIZE
else:
    perp = (xx + yy - SIZE) / np.sqrt(2.0)
    x0, y0, x1, y1 = SIZE, 0, 0, SIZE
d_line = np.abs(perp)

# hairline on dry wall: anti-aliased, ~2 px
hair_alpha = np.clip(1.0 - (d_line - 0.8) / 1.2, 0.0, 1.0)

# --- the bleed: inside the patch, the line's ink travels to the patch's edges -
d_edge = distance_transform_edt(mask)          # distance to the patch's own edge
wob = gaussian_filter(rng.random((SIZE, SIZE)), sigma=8)
wob = (wob - wob.mean()) / (wob.std() + 1e-9)
d_line_eff = np.clip(d_line + wob * 18.0, 0.0, None)   # wobbled bleed front
t = np.clip(d_line_eff / (d_line_eff + d_edge + 1e-6), 0.0, 1.0)  # 0 at the line, 1 at the edge
wash = 0.30 * t ** 1.4                         # faint wash through the wet patch
u = np.clip((t - 0.72) / 0.28, 0.0, 1.0)
rim = 0.80 * u * u * (3.0 - 2.0 * u)           # dark where the bleed dries: at the edges
bloom = gaussian_filter(wash + rim, sigma=2.0)
bloom_alpha = np.where(mask, bloom, 0.0) * m

# inside the patch the hairline's ink has left the line for the edges
hair_alpha = np.where(mask, 0.0, hair_alpha * 0.85)

# --- compose ------------------------------------------------------------------
wall = np.tile(PAPER, (SIZE, SIZE, 1))
wet = WET_TINT + streak[..., None] * 1.5       # faint sheen of clean water
wall = wall * (1 - m[..., None]) + wet * m[..., None]

ink_layer = np.clip(hair_alpha + bloom_alpha, 0.0, 1.0)[..., None]
wall = wall * (1 - ink_layer) + INK * ink_layer

img = Image.fromarray(np.clip(wall, 0, 255).astype(np.uint8))
img.save("render-1.png", optimize=True)

print(f"diagonal: {'top-left to bottom-right' if diag_choice == 0 else 'top-right to bottom-left'}")
print(f"patch center: ({cx:.0f}, {cy:.0f}) vs wall center (1000, 1000)")
print(f"patch area: {patch_area_frac:.4f} of the wall")
print(f"elongation: {elong:.2f} at {np.degrees(elong_angle):.1f} deg")
