#!/usr/bin/env python3
"""
Wall drawing, 2026-11-12.

    Brush five strokes of clean water up and down the wall at chance places and
    heights, dry wall between. While wet, draw one black ink line, not straight,
    through all five. Sharp on dry wall, in each stroke it bleeds up and down to
    the ends and dries dark there.

Run from inside this directory:  python3 champion.py
Writes renders-champion/render-1.png, square, 2500 px.
"""

import os
import numpy as np
from scipy.ndimage import gaussian_filter, gaussian_filter1d
from scipy.interpolate import PchipInterpolator
from PIL import Image

S = 2500
SEED = int(os.environ.get("SEED", "2210"))
OUT = os.environ.get("OUT", "renders-champion/render-1.png")
rng = np.random.default_rng(SEED)

f32 = np.float32


def noise1d(n, sigma, rs=None):
    r = rs if rs is not None else rng
    v = r.standard_normal(n).astype(f32)
    v = gaussian_filter1d(v, sigma, mode="reflect")
    s = v.std()
    return v / (s + 1e-9)


def fbm(shape, scales, weights, rs=None):
    r = rs if rs is not None else rng
    out = np.zeros(shape, dtype=f32)
    for sc, w in zip(scales, weights):
        n = r.standard_normal(shape).astype(f32)
        n = gaussian_filter(n, sc, mode="reflect")
        n /= n.std() + 1e-9
        out += f32(w) * n
    return out


def smoothstep(t):
    t = np.clip(t, 0.0, 1.0)
    return t * t * (3.0 - 2.0 * t)


# ---------------------------------------------------------------- the wall ---
# Plaster: broad mottling, trowel drift, fine tooth.
wall = 0.952 + 0.013 * fbm((S, S), (320.0, 120.0, 44.0), (0.6, 0.35, 0.22))
wall += 0.006 * fbm((S, S), (9.0, 3.0), (0.6, 0.45))
tooth = rng.standard_normal((S, S)).astype(f32)
tooth = gaussian_filter(tooth, 0.7, mode="reflect")
wall += 0.0075 * tooth / (tooth.std() + 1e-9)
# faint uneven light across the wall
gy, gx = np.mgrid[0:S, 0:S].astype(f32)
wall += 0.012 * ((gx / S) * 0.5 + (1.0 - gy / S) * 0.5 - 0.5)
del gy, gx, tooth
wall = np.clip(wall, 0.0, 1.0).astype(f32)

# ------------------------------------------------------- five water strokes ---
# Chance places (x) with dry wall between, chance heights (extent and position).
N_STROKES = 5
margin_x = 180
while True:
    xs = np.sort(rng.uniform(margin_x, S - margin_x, N_STROKES))
    if np.all(np.diff(xs) > 300):
        break

strokes = []
Wmap = np.zeros((S, S), dtype=f32)  # wetness, for the faint water trace

for i in range(N_STROKES):
    length = rng.uniform(760, 1950)
    y0 = rng.uniform(120, S - 120 - length)
    y1 = y0 + length
    r0, r1 = int(np.floor(y0)) - 4, int(np.ceil(y1)) + 5
    r0, r1 = max(0, r0), min(S, r1)
    rows = np.arange(r0, r1, dtype=f32)

    halfw0 = rng.uniform(42, 96)
    # brush wander and pressure along the stroke
    cx = xs[i] + 13.0 * noise1d(r1 - r0, 110.0) + 4.0 * noise1d(r1 - r0, 26.0)
    hw = halfw0 * (1.0 + 0.17 * noise1d(r1 - r0, 90.0) + 0.06 * noise1d(r1 - r0, 18.0))
    # rounded, slightly uneven ends where the brush was set down and lifted
    cap_a = rng.uniform(16, 58)
    cap_b = rng.uniform(16, 58)
    t_in = np.clip((rows - y0) / cap_a, 0, 1)
    t_out = np.clip((y1 - rows) / cap_b, 0, 1)
    taper = np.minimum(t_in, t_out)
    hw = hw * np.sqrt(np.clip(taper * (2.0 - taper), 0.0, 1.0))  # elliptical ends

    c0 = int(max(0, np.floor(cx.min() - halfw0 * 1.5)))
    c1 = int(min(S, np.ceil(cx.max() + halfw0 * 1.5) + 1))
    cols = np.arange(c0, c1, dtype=f32)

    d = np.abs(cols[None, :] - cx[:, None])
    edge = rng.uniform(4.0, 9.0)
    wet = smoothstep((hw[:, None] - d) / edge + 0.5)
    # bristle streaks: wetness varies across the brush, along its length
    streak = 1.0 - 0.13 * np.abs(noise1d(c1 - c0, 2.6))[None, :]
    wet = wet * streak.astype(f32)
    wet *= np.clip(taper, 0, 1)[:, None] * 0.15 + 0.85
    wet = np.clip(wet, 0.0, 1.0).astype(f32)

    strokes.append(dict(r0=r0, r1=r1, c0=c0, c1=c1, wet=wet, y0=y0, y1=y1, x=xs[i]))
    np.maximum(Wmap[r0:r1, c0:c1], wet, out=Wmap[r0:r1, c0:c1])

# ----------------------------------------------------------- the ink line ---
# One line, not straight, that passes through all five wet strokes. Its control
# points sit inside each stroke's vertical extent; the rest is free hand.
ctrl_x = [0.0]
ctrl_y = [None]
for s in strokes:
    lo = s["y0"] + 0.22 * (s["y1"] - s["y0"])
    hi = s["y1"] - 0.22 * (s["y1"] - s["y0"])
    ctrl_x.append(s["x"] + rng.uniform(-30, 30))
    ctrl_y.append(rng.uniform(lo, hi))
inner = np.array(ctrl_y[1:], dtype=float)
ctrl_y[0] = float(np.clip(inner[0] + rng.uniform(-240, 240), 160, S - 160))
ctrl_x.append(float(S - 1))
ctrl_y.append(float(np.clip(inner[-1] + rng.uniform(-240, 240), 160, S - 160)))

ctrl_x = np.array(ctrl_x, dtype=float)
ctrl_y = np.array(ctrl_y, dtype=float)
order = np.argsort(ctrl_x)
yline = PchipInterpolator(ctrl_x[order], ctrl_y[order])(np.arange(S, dtype=float))
# free-hand wander and tremor, small enough to keep the crossings inside
yline = yline + 26.0 * noise1d(S, 230.0) + 8.0 * noise1d(S, 40.0) + 1.1 * noise1d(S, 11.0)
yline = yline.astype(f32)

# nib width: a little pressure variation, sharp edges
lw = 5.0 + 0.95 * noise1d(S, 160.0) + 0.35 * noise1d(S, 24.0)
lw = np.clip(lw, 3.0, 7.0).astype(f32)
load = np.clip(1.0 + 0.16 * noise1d(S, 70.0) + 0.09 * noise1d(S, 11.0), 0.6, 1.3).astype(f32)

ink = np.zeros((S, S), dtype=f32)

# sharp track, masked off where the wall is wet (there it blooms instead)
wet_soft = np.clip(Wmap / 0.55, 0.0, 1.0)
for x in range(S):
    yl = float(yline[x])
    h = float(lw[x])
    a = int(np.floor(yl - h - 2.0))
    b = int(np.ceil(yl + h + 2.0)) + 1
    a, b = max(0, a), min(S, b)
    if b <= a:
        continue
    yy = np.arange(a, b, dtype=f32)
    prof = np.clip(h - np.abs(yy - yl) + 0.5, 0.0, 1.0)  # sharp, antialiased edge
    ink[a:b, x] += prof * load[x] * (1.0 - wet_soft[a:b, x])

# ------------------------------------------------- bleeding in each stroke ---
# In a wet stroke the nib's ink is drawn out of the track: it runs up and down
# the column of water, fades as it goes, and piles at the top and bottom ends
# of the stroke, where the water stops and dries dark.
A_CORE, A_MID, A_RUN, A_END, FLOOR = 0.95, 0.52, 0.17, 1.60, 0.011
for s in strokes:
    r0, r1, c0, c1 = s["r0"], s["r1"], s["c0"], s["c1"]
    wet = s["wet"]
    nc = c1 - c0
    bloom = np.zeros_like(wet)
    # per-column character of the bleed
    jl = 1.0 + 0.30 * noise1d(nc, 7.0)
    je = 1.0 + 0.34 * noise1d(nc, 5.0)
    jt = 1.0 + 0.28 * noise1d(nc, 9.0)
    lam_base = rng.uniform(17, 31)
    # the water body is connected, so the reach of the bleed and how far the ink
    # has to go are properties of the whole stroke, not of one column
    s_span = float(s["y1"] - s["y0"])
    L_s = float(np.clip(0.24 * s_span, 70.0, 270.0))
    thin = float(np.clip((700.0 / s_span) ** 0.5, 0.55, 1.10))
    # Pass 1: where the water stands in each column, and where it stops.
    t_arr = np.zeros(nc, dtype=np.int32)
    b_arr = np.zeros(nc, dtype=np.int32)
    valid = np.zeros(nc, dtype=bool)
    for j in range(nc):
        x = c0 + j
        col = wet[:, j]
        if col.max() < 0.45:
            continue
        yi = int(round(float(yline[x]))) - r0
        if yi < 0 or yi >= col.shape[0] or col[yi] < 0.35:
            continue
        dry = np.flatnonzero(col < 0.35)
        above = dry[dry < yi]
        below = dry[dry > yi]
        t = int(above.max() + 1) if above.size else 0
        b = int(below.min() - 1) if below.size else col.shape[0] - 1
        if b - t < 8:
            continue
        t_arr[j], b_arr[j], valid[j] = t, b, True
    if not valid.any():
        continue
    # Ink piles up only where the water's edge stands across its path. On the
    # ragged sides of a stroke the edge runs with the ink, so nothing collects.
    iv = np.flatnonzero(valid)
    xs_all = np.arange(nc)
    t_s = gaussian_filter1d(np.interp(xs_all, iv, t_arr[iv]).astype(f32), 3.0)
    b_s = gaussian_filter1d(np.interp(xs_all, iv, b_arr[iv]).astype(f32), 3.0)
    w_t = 1.0 / (1.0 + (np.abs(np.gradient(t_s)) / 6.0) ** 2)
    w_b = 1.0 / (1.0 + (np.abs(np.gradient(b_s)) / 6.0) ** 2)

    # Pass 2: the ink runs up and down the water and dries at the stops.
    for j in iv:
        x = c0 + j
        col = wet[:, j]
        t, b = int(t_arr[j]), int(b_arr[j])
        yl = float(yline[x])
        yi = int(round(yl)) - r0
        yy = np.arange(t, b + 1, dtype=f32)
        d = np.abs(yy - (yl - r0))
        span = float(b - t + 1)
        L = L_s * max(0.55, jl[j])
        lam_t = lam_base * max(0.45, je[j]) * 0.92
        lam_b = lam_base * max(0.45, jt[j]) * 1.18
        nib = float(lw[x] * load[x]) / 5.0 * float(min(1.0, col[yi]))
        ends = A_END * float(np.clip(span / 420.0, 0.45, 1.0))
        p = (A_CORE * np.exp(-0.5 * (d / 11.0) ** 2)
             + A_MID * np.exp(-(d / 72.0))
             + A_RUN * thin * np.exp(-(d / L))
             + FLOOR * thin
             + ends * (0.88 * w_t[j] * np.exp(-(yy - t) / lam_t)
                       + 1.12 * w_b[j] * np.exp(-(b - yy) / lam_b)))
        p = p * nib
        shape = np.clip(col[t:b + 1] / 0.70, 0.0, 1.0) ** 0.6  # held by the water's own edge
        bloom[t:b + 1, j] += p * shape
    if bloom.max() <= 0:
        continue
    gran = 1.0 + 0.18 * fbm(bloom.shape, (26.0, 7.0, 2.0), (0.5, 0.45, 0.35))
    bloom = gaussian_filter(bloom, (1.2, 3.4), mode="nearest") * np.clip(gran, 0.35, 1.9)
    ink[r0:r1, c0:c1] += bloom

ink = np.clip(ink, 0.0, 3.0)

# ------------------------------------------------------------- composite ---
# Clean water on a wall is nearly invisible once dry; left as the faintest trace.
base = wall - 0.0050 * Wmap

alpha = 1.0 - np.exp(-3.5 * ink)
wall_rgb = np.stack([base * 1.000, base * 0.9905, base * 0.9735], axis=-1)
ink_rgb = np.array([0.075, 0.072, 0.082], dtype=f32)
img = wall_rgb * (1.0 - alpha[..., None]) + ink_rgb[None, None, :] * alpha[..., None]

grain = rng.standard_normal((S, S)).astype(f32)
grain = gaussian_filter(grain, 0.6, mode="reflect")
img += 0.0055 * (grain / (grain.std() + 1e-9))[..., None]

img = np.clip(img, 0.0, 1.0)
out = (np.round(img * 255.0)).astype(np.uint8)
os.makedirs(os.path.dirname(OUT) or ".", exist_ok=True)
Image.fromarray(out, "RGB").save(OUT)
print("wrote", OUT, out.shape, "seed", SEED)
