"""Shared bits for the yohaku pieces: canvas size, colours, noise, paper grain.

Every piece is a file next to this one with a render(seed) function that
returns a 3840x2160 RGB PIL image. Run a piece directly to get a PNG:

    python awa.py          # uses the published seed
    python awa.py 5        # or try another one
"""
import math
import numpy as np
from PIL import Image

W, H = 3840, 2160

# Japanese traditional colours (hex values from the usual reference charts)
C = {
    "kinari": "#fbfaf5", "sumi": "#2b2b2b", "nibi": "#727171", "ai": "#165e83",
    "gunjo": "#4c6cb3", "shu": "#eb6101", "kurenai": "#d7003a", "yamabuki": "#f8b500",
    "wakatake": "#68be8d", "sakura": "#fef4f4", "kon": "#223a70", "hai": "#c8c2be",
    "uguisu": "#928c36", "tokiwa": "#007b43", "fuji": "#bbc8e6", "kuchiba": "#e0815e",
    "yoru": "#1b1d2a", "tsuki": "#f1ead6",
}


def rgb(h):
    h = h.lstrip("#")
    return tuple(int(h[i:i + 2], 16) for i in (0, 2, 4))


def value_noise(w, h, scale, octaves, rng):
    """Smoothstep-interpolated value noise in [0, 1], a few octaves stacked."""
    out = np.zeros((h, w))
    amp, tot = 1.0, 0.0
    for o in range(octaves):
        s = max(2, int(scale * (2 ** o)))
        gy, gx = s + 2, int(s * w / h) + 2
        g = rng.random((gy, gx))
        y = np.linspace(0, s, h); x = np.linspace(0, s * w / h, w)
        yi, xi = np.floor(y).astype(int), np.floor(x).astype(int)
        fy, fx = y - yi, x - xi
        fy, fx = fy * fy * (3 - 2 * fy), fx * fx * (3 - 2 * fx)
        a = g[yi][:, xi]; b = g[yi][:, xi + 1]; c = g[yi + 1][:, xi]; d = g[yi + 1][:, xi + 1]
        top = a + (b - a) * fx; bot = c + (d - c) * fx
        out += amp * (top + (bot - top) * fy[:, None]); tot += amp; amp *= 0.5
    return out / tot


def smooth1d(n, rng, waves=6, base=1.0):
    """A wobbly 1-D curve in [0, 1] made from a few sines."""
    x = np.linspace(0, 1, n); y = np.zeros(n)
    for k in range(waves):
        f = base * (1.6 ** k) * rng.uniform(0.8, 1.3)
        y += np.sin(x * math.tau * f + rng.random() * math.tau) / (1.7 ** k)
    return (y - y.min()) / (y.max() - y.min())


def paper(img, rng, strength=6):
    """Light gaussian grain so flat colour looks a bit like paper.

    Done in bands of rows to keep memory low; the noise comes out of the
    generator in the same order as one big normal() call, so it's the same image.
    """
    a = np.asarray(img)
    out = np.empty_like(a)
    for y in range(0, a.shape[0], 120):
        band = a[y:y + 120].astype(np.int16)
        n = rng.normal(0, strength, band.shape[:2])[..., None]
        out[y:y + 120] = np.clip(band + n, 0, 255).astype(np.uint8)
    return Image.fromarray(out)


def cli(render, seed):
    """Command-line helper used at the bottom of each piece."""
    import os, sys
    if len(sys.argv) > 1:
        seed = int(sys.argv[1])
    name = os.path.splitext(os.path.basename(sys.argv[0]))[0]
    render(seed).convert("RGB").save(f"{name}.png")
    print(f"{name}.png  (seed {seed})")
