#!/usr/bin/env python3
"""3-D reconstruction of the gastric lumen gas cast (CT, non-contrast).

Labelling policy for this figure:
  * every label states what was MEASURED from the segmentation
  * no named landmark (cardia, EGJ, hiatus, angle of His) is asserted - none of
    them can be localised from a gas cast
  * orientation letters are given only for views where they are unambiguous
"""
import pickle

import numpy as np
from PIL import Image, ImageDraw, ImageFont
from scipy import ndimage as ndi

SP = "/private/tmp/claude-501/-Users-macbookpro-Documents-MRI-and-CT/d77db81a-16a7-433c-9e92-e9e0e5aecdfb/scratchpad"
FB = "/System/Library/Fonts/Supplemental/Arial Bold.ttf"
F, FS, FT = ImageFont.truetype(FB, 17), ImageFont.truetype(FB, 13), ImageFont.truetype(FB, 15)
CY = (255, 214, 64)


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")
    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)
    return np.where(Br, Vr, -1000.), ndi.gaussian_filter(Sr, 1.2), sz


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, .0032, a); rgb[s] = (.70, .43, .34)
    return rgb, a


def render(Vr, Sf, yaw, pitch=0.):
    v, s = Vr, Sf
    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)
    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)
    nz, ny, nx = v.shape
    solid = s > .5
    hit = solid.any(axis=1)
    idx = np.argmax(solid, axis=1)

    gz, gy, gx = np.gradient(s)
    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) ** 28
    rim = (1 - np.clip(np.abs(N[..., 1]), 0, 1)) ** 2.2
    sh = (.20 + .80 * dif) * (1 - .30 * idx / ny)
    stom = (np.array((.94, .38, .26))[None, None, :] * sh[..., None]
            + .38 * spe[..., None] + .16 * rim[..., None] * np.array([1, .6, .45]))

    out = np.zeros((nz, nx, 3), np.float32)
    T = np.ones((nz, nx), np.float32)
    for j in range(ny):
        act = (~hit) | (j < idx)
        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 * hit)[..., None] * stom
    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 dress(arr, name, sz, lr=None, bar=30, up=2.4):
    im = Image.fromarray(arr)
    im = im.resize((int(im.size[0] * up), int(im.size[1] * up)), Image.LANCZOS)
    sz = sz / up
    W, H = im.size
    d = ImageDraw.Draw(im)
    d.text((8, 6), name, fill=CY, font=FT)
    d.text((W // 2, 6), "S", fill=(150, 220, 255), font=FS, anchor="ma")
    d.text((W // 2, H - 34), "I", fill=(150, 220, 255), font=FS, anchor="ma")
    if lr:
        d.text((6, H // 2), lr[0], fill=(150, 220, 255), font=FS, anchor="lm")
        d.text((W - 6, H // 2), lr[1], fill=(150, 220, 255), font=FS, anchor="rm")
    px = int(bar / sz)
    d.line([(10, H - 14), (10 + px, H - 14)], fill=(255, 255, 255), width=3)
    d.text((10, H - 30), f"{bar} mm", fill=(255, 255, 255), font=FS)
    return im


if __name__ == "__main__":
    g = pickle.load(open(f"{SP}/geo.pkl", "rb"))
    sto = np.load(f"{SP}/ct_stomach_gas.npy")
    vox = g["sz"] * g["sy"] * g["sx"] / 1000
    zz, jj, ii = np.where(sto)
    vol = sto.sum() * vox
    cc = (zz.max() - zz.min()) * g["sz"]
    xr = (g["x0"] + ii.min() * g["sx"], g["x0"] + ii.max() * g["sx"])
    zr = (g["z_top"] - zz.min() * g["sz"], g["z_top"] - zz.max() * g["sz"])
    print(f"cast {vol:.1f} mL  cc {cc:.0f} mm  x {xr[0]:.0f}..{xr[1]:.0f}  z {zr[0]:.0f}..{zr[1]:.0f}")

    Vr, Sf, sz = build(-372, -492, -35, 145)
    views = [(0, 0, "ANTERIOR (AP)", ("R", "L")), (-35, 0, "LAO 35", None),
             (-70, 0, "LAO 70", None), (35, 0, "RAO 35", None),
             (-35, 25, "LAO 35 / caudal tilt", None), (180, 0, "POSTERIOR (PA)", ("L", "R"))]
    tiles = [dress(tone(render(Vr, Sf, y, p)), n, sz, lr) for y, p, n, lr in views]
    for _, _, n, _ in views:
        print("rendered", n)

    w, h = tiles[0].size
    head, foot = 62, 46
    sheet = Image.new("RGB", (w * 3, h * 2 + head + foot), (8, 8, 10))
    for i, t in enumerate(tiles):
        sheet.paste(t, ((i % 3) * w, (i // 3) * h + head))
    d = ImageDraw.Draw(sheet)
    d.text((12, 8), "STOMACH - 3D RECONSTRUCTION OF THE GAS-FILLED LUMEN", fill=CY, font=F)
    d.text((12, 30), f"CT abdomen, non-contrast, 2026-07-22  -  segmented at < -500 HU  -  "
                     f"cast volume {vol:.1f} mL, cranio-caudal extent {cc:.0f} mm, "
                     f"x {xr[0]:+.0f} to {xr[1]:+.0f} mm (patient left), z {zr[0]:.0f} to {zr[1]:.0f} mm",
           fill=(185, 185, 185), font=FS)
    y0 = h * 2 + head + 6
    d.text((12, y0), "WHAT THIS IS:  the gas-filled part of the gastric lumen only. "
                     "Fluid-filled lumen and the gastric wall are NOT included, so the cast "
                     "under-represents the true stomach.",
           fill=(255, 150, 150), font=FS)
    d.text((12, y0 + 18), "NOT SHOWN:  cardia, oesophagogastric junction, hiatus and angle of His "
                          "are wall/oesophageal landmarks and cannot be located from a gas cast - "
                          "no such label is made here.",
           fill=(255, 150, 150), font=FS)
    sheet.save(f"{SP}/FIG_stomach_3D_final.png")
    print("saved", sheet.size)

    frames = []
    for yaw in range(0, 360, 10):
        im = Image.fromarray(tone(render(Vr, Sf, yaw - 180)))
        im = im.resize((im.size[0] * 2, im.size[1] * 2), Image.LANCZOS)
        d = ImageDraw.Draw(im)
        d.text((10, 8), "Stomach - gas-filled lumen cast (CT)", fill=CY, font=FT)
        d.text((10, 28), f"{vol:.1f} mL  |  rotation {yaw}deg  |  gas only, wall not included",
               fill=(190, 190, 190), font=FS)
        px = int(30 / sz) * 2
        d.line([(14, im.size[1] - 18), (14 + px, im.size[1] - 18)], fill=(255, 255, 255), width=3)
        d.text((14, im.size[1] - 36), "30 mm", fill=(255, 255, 255), font=FS)
        frames.append(im)
        print("frame", yaw, flush=True)
    frames[0].save(f"{SP}/FIG_stomach_3D_final.gif", save_all=True,
                   append_images=frames[1:], duration=110, loop=0, optimize=True)
    print("saved gif")
