"""An imagined recording studio. Uses the Broadsheet cel-still paper and optics primitives."""
import argparse
import math
from pathlib import Path
from typing import Sequence
import cairo
import cv2
import numpy as np
from PIL import Image

def screen_blend(
    dst_rgb: np.ndarray, add_rgb: np.ndarray, strength: float = 1.0
) -> np.ndarray:
    b = np.clip(add_rgb * strength, 0.0, 1.0)
    return 1.0 - (1.0 - dst_rgb) * (1.0 - b)

def fbm_gouache(
    h: int,
    w: int,
    octaves: Sequence[tuple[float, float, float]] = (
        (72.0, 68.0, 0.45),
        (26.0, 29.0, 0.32),
        (10.5, 9.5, 0.16),
        (4.5, 4.8, 0.07),
    ),
    seed: int = 101,
) -> np.ndarray:
    """Multi-octave bicubic-upsampled zero-mean unit-variance Gaussian mottling
    at balanced square scales (never stretched row/column striping on fills)."""
    rng = np.random.default_rng(seed)
    acc = np.zeros((h, w), dtype=np.float32)
    w_sum = 0.0
    for sx, sy, weight in octaves:
        gh = max(4, int(round(h / float(sy))))
        gw = max(4, int(round(w / float(sx))))
        grid = rng.standard_normal((gh, gw)).astype(np.float32)
        up = cv2.resize(grid, (w, h), interpolation=cv2.INTER_CUBIC)
        acc += float(weight) * up
        w_sum += float(weight)
    acc /= max(w_sum, 1e-6)
    std = float(np.std(acc))
    if std > 1e-6:
        acc = (acc - float(np.mean(acc))) / std
    return acc.astype(np.float32)

def make_paper_tooth(h: int, w: int, seed: int = 707) -> np.ndarray:
    """Fine isotropic cold-press paperboard tooth."""
    fine = fbm_gouache(h, w, octaves=((3.6, 3.8, 0.55), (1.9, 2.0, 0.45)), seed=seed)
    med = fbm_gouache(h, w, octaves=((11.0, 10.5, 1.0),), seed=seed + 19)
    return np.clip(0.72 * fine + 0.28 * med, -2.5, 2.5).astype(np.float32)

def finish_35mm_optics(
    rgb: np.ndarray,
    specular_glints: np.ndarray | None = None,
    seed: int = 909,
) -> np.ndarray:
    """Float32 35mm cinema optics + restrained analog transfer finish."""
    img = np.clip(rgb.astype(np.float32), 0.0, 1.0)
    h, w, _ = img.shape

    lum = 0.2126 * img[:, :, 0] + 0.7152 * img[:, :, 1] + 0.0722 * img[:, :, 2]
    bright = np.clip((lum - 0.72) / 0.28, 0.0, 1.0) ** 1.30
    if specular_glints is not None:
        bright = np.clip(bright + specular_glints * 0.88, 0.0, 1.38)

    hal_tint = np.array([1.00, 0.90, 0.74], dtype=np.float32)
    h_src = bright[:, :, None] * hal_tint[None, None, :]
    halation = (
        0.17 * cv2.GaussianBlur(h_src, (0, 0), 6.5)
        + 0.16 * cv2.GaussianBlur(h_src, (0, 0), 24.0)
        + 0.14 * cv2.GaussianBlur(h_src, (0, 0), 72.0)
    )
    img = screen_blend(img, halation, strength=1.0)

    yy, xx = np.mgrid[0:h, 0:w].astype(np.float32)
    nx = (xx - w * 0.5) / (w * 0.5)
    ny = (yy - h * 0.5) / (h * 0.5)
    r2 = nx * nx + ny * ny

    ca_scale = 0.00085
    img[:, :, 0] = cv2.remap(
        img[:, :, 0],
        (xx + (xx - w * 0.5) * r2 * ca_scale).astype(np.float32),
        (yy + (yy - h * 0.5) * r2 * ca_scale).astype(np.float32),
        interpolation=cv2.INTER_LINEAR,
        borderMode=cv2.BORDER_REFLECT_101,
    )
    img[:, :, 2] = cv2.remap(
        img[:, :, 2],
        (xx - (xx - w * 0.5) * r2 * ca_scale).astype(np.float32),
        (yy - (yy - h * 0.5) * r2 * ca_scale).astype(np.float32),
        interpolation=cv2.INTER_LINEAR,
        borderMode=cv2.BORDER_REFLECT_101,
    )
    img *= (1.0 - 0.155 * np.clip(r2 - 0.16, 0.0, 2.0))[:, :, None]

    black_lift = np.array([0.018, 0.016, 0.022], dtype=np.float32)
    img = black_lift[None, None, :] + img * (1.0 - black_lift[None, None, :])
    knee, ceiling = 0.80, 0.965
    span = ceiling - knee
    above = np.maximum(img - knee, 0.0)
    img = np.where(img > knee, knee + span * np.tanh(above / span), img)

    rng = np.random.default_rng(seed)
    lum2 = 0.2126 * img[:, :, 0] + 0.7152 * img[:, :, 1] + 0.0722 * img[:, :, 2]
    env = np.clip(1.12 - 0.95 * (np.clip(lum2, 0.0, 1.0) ** 1.55), 0.12, 1.12)
    g_fine = rng.standard_normal((h, w)).astype(np.float32)
    g_clump = cv2.resize(
        rng.standard_normal((max(2, h // 2), max(2, w // 2))).astype(np.float32),
        (w, h),
        interpolation=cv2.INTER_LINEAR,
    )
    g_chroma = cv2.resize(
        rng.standard_normal((max(2, h // 2), max(2, w // 2), 3)).astype(np.float32),
        (w, h),
        interpolation=cv2.INTER_LINEAR,
    )
    img = np.clip(
        img + (0.0150 * (0.58 * g_fine + 0.42 * g_clump)[:, :, None] + 0.0042 * g_chroma) * env[:, :, None],
        0.0,
        1.0,
    )

    r_ch, g_ch, b_ch = img[:, :, 0], img[:, :, 1], img[:, :, 2]
    y_ch = 0.299 * r_ch + 0.587 * g_ch + 0.114 * b_ch
    i_ch = 0.596 * r_ch - 0.274 * g_ch - 0.322 * b_ch
    q_ch = 0.211 * r_ch - 0.523 * g_ch + 0.312 * b_ch

    i_soft = cv2.GaussianBlur(i_ch, (0, 0), sigmaX=1.05, sigmaY=0.15, borderType=cv2.BORDER_REFLECT_101)
    q_soft = cv2.GaussianBlur(q_ch, (0, 0), sigmaX=1.15, sigmaY=0.15, borderType=cv2.BORDER_REFLECT_101)
    y_blur = cv2.GaussianBlur(y_ch, (0, 0), sigmaX=0.85, sigmaY=0.05, borderType=cv2.BORDER_REFLECT_101)
    y_out = np.clip(y_ch + 0.07 * (y_ch - y_blur), 0.0, 1.0)

    out = np.empty_like(img)
    out[:, :, 0] = y_out + 0.956 * i_soft + 0.621 * q_soft
    out[:, :, 1] = y_out - 0.272 * i_soft - 0.647 * q_soft
    out[:, :, 2] = y_out - 1.106 * i_soft + 1.703 * q_soft
    out = np.clip(out, 0.0, 1.0)

    row_shift = rng.normal(0.0, 0.072, size=h).astype(np.float32)
    row_shift = cv2.GaussianBlur(row_shift[:, None], (1, 5), 0.9)[:, 0]
    out = cv2.remap(
        out,
        (xx + row_shift[:, None]).astype(np.float32),
        yy,
        interpolation=cv2.INTER_LINEAR,
        borderMode=cv2.BORDER_REFLECT_101,
    )
    scan = 1.0 - 0.0065 * (0.5 - 0.5 * np.cos(math.pi * yy))
    return np.clip(out * scan[:, :, None], 0.0, 1.0)

W, H = 2048, 1152
surface = cairo.ImageSurface(cairo.FORMAT_RGB24, W, H)
c = cairo.Context(surface)
c.scale(2, 2)

def color(h):
    return [int(h[i:i+2], 16) / 255 for i in (0, 2, 4)]

def fill(h):
    c.set_source_rgb(*color(h))
    c.fill()

def polygon(points, h):
    c.new_path()
    c.move_to(*points[0])
    for p in points[1:]:
        c.line_to(*p)
    c.close_path()
    fill(h)

def line(points, h, width=1):
    c.new_path()
    c.move_to(*points[0])
    for p in points[1:]:
        c.line_to(*p)
    c.set_line_cap(cairo.LINE_CAP_ROUND)
    c.set_line_width(width)
    c.set_source_rgb(*color(h))
    c.stroke()

def glow(x, y, sx, sy, rgb, opacity):
    c.save()
    c.translate(x, y)
    c.scale(sx, sy)
    p = cairo.RadialGradient(0, 0, 0, 0, 0, 1)
    p.add_color_stop_rgba(0, *color(rgb), opacity)
    p.add_color_stop_rgba(0.52, *color(rgb), opacity * 0.5)
    p.add_color_stop_rgba(1, *color(rgb), 0)
    c.set_source(p)
    c.arc(0, 0, 1, 0, 6.29)
    c.fill()
    c.restore()

# Several depth bands: dark acoustic wall, wood floor, pool of light,
# empty music stand, then cello. This is not a depiction of the real studio.
for a,b,h in [(0,167,'292827'),(167,333,'2D2B28'),(333,513,'302C28'),
              (513,837,'332D28'),(837,1024,'2A2826')]:
    polygon([(a,0),(b,0),(b,391),(a,391)],h)
    line([(a+1,0),(a+1,368)],'252321',2)
glow(679, 154, 468, 347, 'D5AB76', 0.36)
polygon([(0,376),(1024,349),(1024,576),(0,576)],'3A312A')
for i in range(9):
    x=-210+i*199
    line([(620+(x-620)*0.28,361),(x,577)],'302922',1.3)
for y in (376,403,443,497,570):
    line([(0,y+12),(1024,y-11)],'4C3F33',1.1)
glow(642, 495, 392, 113, 'E5A56C', 0.53)
glow(622, 520, 126, 27, '201C1A', 0.62)
glow(383, 510, 115, 20, '201C1A', 0.63)

# Sheet music: marks are invented, not a reproduction of the score.
line([(396,321),(393,483)],'22211E',6)
for p in [(355,512),(431,510),(412,491)]:
    line([(393,479),p],'272522',4)
polygon([(306,225),(455,218),(466,324),(320,331)],'322C26')
polygon([(315,225),(448,220),(456,316),(327,320)],'CAAF85')
polygon([(321,224),(379,228),(388,310),(333,320)],'EDE0B8')
polygon([(379,228),(445,221),(452,310),(388,310)],'E4CCA1')
for y in (247,268,289):
    for j in range(5):
        line([(332,y+j*2),(375,y+j*2)],'9F8968',0.5)
        line([(390,y+j*2),(438,y+j*2-2)],'9F8968',0.5)
    for x in (343,358,403,427):
        c.arc(x,y+4+(x%3),1.5,0,6.29); fill('74654F')
line([(317,323),(467,317)],'241F1D',5)

# Cello, slightly inclined as if left on a stand.
c.save(); c.translate(632,337); c.rotate(0.16)
line([(0,130),(0,175)],'282423',4)
def body(dx=0, dy=0):
    c.save(); c.translate(dx,dy); c.new_path(); c.move_to(0,-73)
    c.curve_to(45,-79,53,-53,42,-33)
    c.curve_to(33,-18,43,-5,54,8)
    c.curve_to(82,35,77,93,48,120)
    c.curve_to(28,140,-28,140,-48,120)
    c.curve_to(-77,93,-82,35,-54,8)
    c.curve_to(-43,-5,-33,-18,-42,-33)
    c.curve_to(-53,-53,-45,-79,0,-73)
    c.close_path(); c.restore()
body(8,5); fill('43261E')
body()
p=cairo.LinearGradient(-78,-64,70,95)
for k,h in [(0,'CD9360'),(.30,'AB603D'),(.71,'8A4430'),(1,'633322')]:
    p.add_color_stop_rgb(k,*color(h))
c.set_source(p); c.fill_preserve()
c.set_line_width(2.8); c.set_source_rgb(*color('512D24')); c.stroke()
c.save(); body(); c.clip()
for i in range(-11,12):
    line([(i*6,-70),(i*6+3,15),(i*6+1,81),(i*6+4,140)], 'A36040', .38)
c.restore()
polygon([(-7,-150),(7,-150),(13,4),(-13,4)],'332723')
polygon([(-12,102),(-5,49),(6,49),(14,102),(0,117)],'362923')
line([(-20,30),(-12,24),(10,23),(19,29)],'E2B47F',4)
for x in (-33,33):
    s=1 if x>0 else -1
    line([(x+s*5,8),(x,17),(x-s*4,34),(x-s*8,44)],'462720',2.4)
    for a,b in [(x+s*5,8),(x-s*8,44)]:
        c.arc(a,b,2.5,0,6.29);fill('462720')
for i in (-4,-1,2,5):
    line([(i*.75,-148),(i,25),(i*.62,92)],'D7BB9D',.52)
line([(0,-151),(0,-180),(5,-190),(10,-192)],'825231',10)
for x,y in [(-8,-169),(8,-173),(-8,-180),(8,-184)]:
    line([(0,y),(x,y)],'322622',4)
c.restore()

def main():
    ap=argparse.ArgumentParser()
    ap.add_argument('--out',type=Path,required=True)
    ap.add_argument('--crops-dir',type=Path)
    opts=ap.parse_args()
    surface.flush()
    bgra=np.ndarray((H,W,4),np.uint8,buffer=surface.get_data())
    rgb=bgra[:,:,[2,1,0]].astype(np.float32)/255
    paper=make_paper_tooth(H,W,seed=31)
    rgb=np.clip(rgb+paper[:,:,None]*np.array([.011,.010,.009]),0,1)
    img=Image.fromarray(np.uint8(np.clip(finish_35mm_optics(rgb),0,1)*255))
    opts.out.parent.mkdir(parents=True,exist_ok=True)
    img.save(opts.out,quality=90,method=6)
    if opts.crops_dir:
        opts.crops_dir.mkdir(parents=True,exist_ok=True)
        for name,x,y in [('light',1195,80),('cello',960,470),('stand',493,370)]:
            img.crop((x,y,x+600,y+450)).save(opts.crops_dir/f'{name}.png')

if __name__ == '__main__':
    main()
