#!/usr/bin/env python3
"""Stomach + diaphragm/hiatus 3D from CT.

Gastric lumen cast = shaded opaque isosurface.
Lung cast = translucent blue; its inferior surface is the diaphragm, so the
gap between the lung bases and the gastric cardia is the hiatus region.
"""
import numpy as np
import pickle
from scipy import ndimage as ndi
from PIL import Image, ImageDraw

SP = "/private/tmp/claude-501/-Users-macbookpro-Documents-MRI-and-CT/d77db81a-16a7-433c-9e92-e9e0e5aecdfb/scratchpad"


def build(z_sup, z_inf, x_lo, x_hi):
    V = np.load(f"{SP}/vol_sup.npy")
    body = np.load(f"{SP}/body_sup.npy")
    sto = np.load(f"{SP}/ct_stomach_gas.npy")
    lun = np.load(f"{SP}/ct_lungs.npy")
    g = pickle.load(open(f"{SP}/geo.pkl", "rb"))
    sz, sy, sx = g["sz"], g["sy"], g["sx"]
    ztop, x0 = g["z_top"], g["x0"]
    k0, k1 = int((ztop - z_sup) / sz), int((ztop - z_inf) / sz)
    i0, i1 = int((x_lo - x0) / sx), int((x_hi - x0) / sx)
    cut = (slice(k0, k1), slice(None), slice(i0, i1))
    zy = sy / sz
    Vr = ndi.zoom(V[cut].astype(np.float32), (1, zy, 1), order=1)
    Br = ndi.zoom(body[cut].astype(np.float32), (1, zy, 1), order=1) > .5
    Sr = ndi.zoom(sto[cut].astype(np.float32), (1, zy, 1), order=1)
    lun = lun.copy()
    kcut = int((ztop + 372) / sz)          # keep only the basal 
    lun[:kcut] = False                     # lung = diaphragm dome proxy
    Lr = ndi.zoom(lun[cut].astype(np.float32), (1, zy, 1), order=1)
    Vr = np.where(Br, Vr, -1000.)
    return (Vr, ndi.gaussian_filter(Sr, 1.2), ndi.gaussian_filter(Lr, 1.6), sz)


def shade(field, idx, ny, base, spec=.38, shine=28, amb=.20):
    gz, gy, gx = np.gradient(field)
    nz, _, nx = field.shape
    kk, ii = np.meshgrid(np.arange(nz), np.arange(nx), indexing="ij")
    N = np.stack([gz[kk, idx, ii], gy[kk, idx, ii], gx[kk, idx, ii]], -1)
    N = -N / (np.linalg.norm(N, axis=-1, keepdims=True) + 1e-8)
    L = np.array([-.45, -.78, -.44]); L /= np.linalg.norm(L)
    Hv = L + np.array([0, -1., 0]); Hv /= np.linalg.norm(Hv)
    dif = np.clip(N @ L, 0, 1)
    spe = np.clip(N @ Hv, 0, 1) ** shine
    rim = (1 - np.clip(np.abs(N[..., 1]), 0, 1)) ** 2.2
    s = (amb + (1 - amb) * dif) * (1 - .30 * idx / ny)
    return (np.array(base)[None, None, :] * s[..., None]
            + spec * spe[..., None] + .16 * rim[..., None] * np.array([1, .6, .45]))


def context_tf(hu):
    a = np.zeros_like(hu)
    rgb = np.zeros(hu.shape + (3,), np.float32)
    b = hu > 220
    a = np.where(b, .105, a); rgb[b] = (.99, .97, .92)
    s = (hu > 15) & (hu < 90) & ~b
    a = np.where(s, .0034, a); rgb[s] = (.72, .44, .34)
    f = (hu > -130) & (hu < -35)
    a = np.where(f, .0013, a); rgb[f] = (.86, .72, .42)
    return rgb, a


def render(Vr, Sf, Lf, yaw, pitch=0., lung_alpha=.16):
    v, s, l = Vr, Sf, Lf
    if pitch:
        v = ndi.rotate(v, pitch, axes=(0, 1), reshape=False, order=1, cval=-1000)
        s = ndi.rotate(s, pitch, axes=(0, 1), reshape=False, order=1, cval=0)
        l = ndi.rotate(l, pitch, axes=(0, 1), reshape=False, order=1, cval=0)
    if yaw:
        v = ndi.rotate(v, yaw, axes=(1, 2), reshape=False, order=1, cval=-1000)
        s = ndi.rotate(s, yaw, axes=(1, 2), reshape=False, order=1, cval=0)
        l = ndi.rotate(l, yaw, axes=(1, 2), reshape=False, order=1, cval=0)
    nz, ny, nx = v.shape

    ssolid = s > .5
    shit = ssolid.any(axis=1); sidx = np.argmax(ssolid, axis=1)
    lsolid = l > .5
    lhit = lsolid.any(axis=1); lidx = np.argmax(lsolid, axis=1)

    stom = shade(s, sidx, ny, (.94, .38, .26))
    lung = shade(l, lidx, ny, (.30, .62, 1.00), spec=.20, shine=20, amb=.38)

    out = np.zeros((nz, nx, 3), np.float32)
    T = np.ones((nz, nx), np.float32)

    # lung surface in front of the stomach
    front = lhit & (~shit | (lidx < sidx))
    out += (T * (lung_alpha * front))[..., None] * lung
    T *= (1 - lung_alpha * front)

    for j in range(ny):
        act = (~shit) | (j < sidx)
        if not act.any():
            break
        rgb, a = context_tf(v[:, j, :])
        a = a * act
        out += (T * a)[..., None] * rgb * (1 - .45 * j / ny)
        T *= (1 - a)

    out += (T * shit)[..., None] * stom
    T *= (1 - shit)
    back = lhit & shit & (lidx > sidx)
    out += (T * (lung_alpha * .6 * back))[..., None] * lung
    return out


def tone(img, gamma=1.85):
    img = np.clip(img, 0, None) / max(img.max(), 1e-6)
    return (np.clip(np.power(img, 1 / gamma), 0, 1) * 255).astype(np.uint8)


def stamp(im, text, sz, mm=50):
    d = ImageDraw.Draw(im)
    d.text((7, 6), text, fill=(255, 240, 140))
    px = int(mm / sz); y = im.size[1] - 15
    d.line([(10, y), (10 + px, y)], fill=(255, 255, 255), width=2)
    d.text((10, y - 13), f"{mm} mm", fill=(255, 255, 255))
    return im


if __name__ == "__main__":
    # wide view: stomach in relation to both hemidiaphragms
    Vr, Sf, Lf, sz = build(-330, -520, -110, 190)
    print("wide ROI", Vr.shape)
    views = [(0, 0, "ANTERIOR (AP)"), (-40, 0, "LAO 40"), (-75, 0, "LAO 75"),
             (40, 0, "RAO 40"), (-40, 22, "LAO 40 / caudal"), (180, 0, "POSTERIOR (PA)")]
    tiles = []
    for yaw, pitch, nm in views:
        tiles.append(stamp(Image.fromarray(tone(render(Vr, Sf, Lf, yaw, pitch))), nm, sz))
        print("  ", nm)
    w, h = tiles[0].size
    sheet = Image.new("RGB", (w * 3, h * 2 + 28), (8, 8, 10))
    for i, t in enumerate(tiles):
        sheet.paste(t, ((i % 3) * w, (i // 3) * h + 28))
    ImageDraw.Draw(sheet).text(
        (8, 7), "CT 3D — gastric lumen cast (orange), lungs/diaphragm (blue), skeleton — "
                "the hiatus lies between the lung bases and the gastric cardia",
        fill=(255, 240, 140))
    sheet.save(f"{SP}/FIG_stomach3d_wide.png")
    print("saved wide", sheet.size)

    # close-up on cardia / hiatus
    Vr, Sf, Lf, sz = build(-370, -490, -30, 140)
    print("close ROI", Vr.shape)
    tiles = []
    for yaw, pitch, nm in [(0, 0, "AP"), (-30, 0, "LAO 30"), (-60, 0, "LAO 60"),
                           (-30, 25, "LAO 30 / caudal"), (30, 0, "RAO 30"), (-90, 0, "LEFT LATERAL")]:
        tiles.append(stamp(Image.fromarray(tone(render(Vr, Sf, Lf, yaw, pitch, lung_alpha=.22))),
                           nm, sz, 30))
        print("  ", nm)
    w, h = tiles[0].size
    sheet = Image.new("RGB", (w * 3, h * 2 + 28), (8, 8, 10))
    for i, t in enumerate(tiles):
        sheet.paste(t, ((i % 3) * w, (i // 3) * h + 28))
    ImageDraw.Draw(sheet).text(
        (8, 7), "CT 3D close-up — gastric cardia / fundus and the diaphragmatic hiatus region",
        fill=(255, 240, 140))
    sheet.save(f"{SP}/FIG_stomach3d_close.png")
    print("saved close", sheet.size)
