#!/usr/bin/env python3
"""Stomach + oesophageal hiatus, CT and MR side by side.

No left-right flipping anywhere: in both studies the column index increases with
DICOM x, which increases towards the patient's LEFT, so displaying the array as-is
already puts patient-left on the viewer's right (radiological convention).

Every label anchor is derived from the segmentation, never hand-placed:
  STOMACH      -> centroid of the gastric lumen mask in that slice
  cardia / EGJ -> most superior voxel of that mask
  diaphragm    -> lowest lung voxel above the stomach (CT only)
"""
import os
import pickle

import numpy as np
import pydicom
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"
ROOT = "MR/DICOM"
TILE = (770, 660)
CY, CM = (255, 212, 64), (105, 240, 255)


def font(sz):
    for p in ("/System/Library/Fonts/Supplemental/Arial Bold.ttf",
              "/System/Library/Fonts/Helvetica.ttc"):
        if os.path.exists(p):
            try:
                return ImageFont.truetype(p, sz)
            except Exception:
                pass
    return ImageFont.load_default()


F, FS = font(16), font(13)


def norm(a, lo=0.5, hi=99.4):
    a = a.astype(np.float32)
    p0, p1 = np.percentile(a, lo), np.percentile(a, hi)
    return np.clip((a - p0) / max(p1 - p0, 1e-6), 0, 1)


def ctwin(a, c=40, w=400):
    return np.clip((a.astype(np.float32) - (c - w / 2)) / w, 0, 1)


def edges(mask):
    b = mask.astype(bool)
    return ndi.binary_dilation(b & ~ndi.binary_erosion(b), iterations=1)


class Tile:
    """One image + overlay, rendered into a fixed-size canvas."""

    def __init__(self, img, mask, px_w, px_h, title, sub, bar_mm=50):
        h, w = img.shape
        ar_w, ar_h = w * px_w, h * px_h                      # true physical size
        k = min((TILE[0] - 16) / ar_w, (TILE[1] - 52) / ar_h)
        self.W, self.H = int(ar_w * k), int(ar_h * k)
        self.sx, self.sy = self.W / w, self.H / h
        self.mm_per_px = px_w / self.sx

        im = Image.fromarray((img * 255).astype(np.uint8)).convert("RGB")
        im = im.resize((self.W, self.H), Image.LANCZOS)
        if mask is not None and mask.any():
            e = Image.fromarray((edges(mask) * 255).astype(np.uint8))
            e = np.array(e.resize((self.W, self.H), Image.BILINEAR)) > 90
            ov = np.zeros((self.H, self.W, 4), np.uint8)
            ov[e] = (*CM, 255)
            o = Image.fromarray(ov, "RGBA")
            im.paste(o, (0, 0), o)
        self.im = im
        self.d = ImageDraw.Draw(im)
        self.title, self.sub, self.bar_mm = title, sub, bar_mm

    def at(self, col, row):
        return int(col * self.sx), int(row * self.sy)

    def arrow(self, col, row, txt, dx=70, dy=-38):
        x, y = self.at(col, row)
        if dx > 0 and x + dx > self.W - 190:
            dx = -abs(dx)
        if dx < 0 and x + dx < 190:
            dx = abs(dx)
        dy = max(dy, 26 - y) if y + dy < 26 else dy
        self.d.line([(x + dx, y + dy), (x, y)], fill=CY, width=2)
        self.d.ellipse([x - 5, y - 5, x + 5, y + 5], outline=CY, width=2)
        self.d.text((x + dx + (5 if dx > 0 else -5), y + dy - 8), txt, fill=CY,
                    font=FS, anchor="la" if dx > 0 else "ra")

    def corner(self, left, right):
        self.d.text((6, self.H - 18), left, fill=(190, 190, 190), font=FS)
        self.d.text((self.W - 6, self.H - 18), right, fill=(190, 190, 190),
                    font=FS, anchor="ra")

    def finish(self):
        px = int(self.bar_mm / self.mm_per_px)
        y = self.H - 34
        self.d.line([(14, y), (14 + px, y)], fill=(255, 255, 255), width=3)
        self.d.text((14, y - 17), f"{self.bar_mm} mm", fill=(255, 255, 255), font=FS)
        c = Image.new("RGB", TILE, (6, 6, 8))
        c.paste(self.im, ((TILE[0] - self.W) // 2, 44 + (TILE[1] - 52 - self.H) // 2))
        d = ImageDraw.Draw(c)
        d.text((10, 8), self.title, fill=CY, font=F)
        d.text((TILE[0] - 10, 12), self.sub, fill=(175, 175, 175), font=FS, anchor="ra")
        return c


def anchors(mask):
    """(centroid_col, centroid_row), (top_col, top_row) of a 2-D mask."""
    rr, cc = np.where(mask)
    if len(rr) == 0:
        return None, None
    top = rr.min()
    return (cc.mean(), rr.mean()), (cc[rr == top].mean(), top)


# ------------------------------------------------------------------ CT
def ct_tiles():
    V = np.load(f"{SP}/vol_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, y0 = g["z_top"], g["x0"], g["y0"]
    K = lambda z: int((ztop - z) / sz)
    I = lambda x: int((x - x0) / sx)
    J = lambda y: int((y - y0) / sy)

    rr, jj, ii = np.where(sto)
    ycen = y0 + jj.mean() * sy
    xcen = x0 + ii.mean() * sx
    ztop_st = ztop - rr.min() * sz
    print(f"CT stomach centroid  y={ycen:.0f}  x={xcen:.0f}   top z={ztop_st:.0f}")
    out = []

    # coronal through the gastric centroid
    j = J(ycen)
    k0, k1, i0, i1 = K(-350), K(-505), I(-115), I(175)
    t = Tile(ctwin(V[k0:k1, j, i0:i1]), sto[k0:k1, j, i0:i1], sx, sz,
             "CT  CORONAL", f"y = {ycen:.0f} mm   (0.83 mm isotropic)")
    cen, top = anchors(sto[k0:k1, j, i0:i1])
    t.arrow(*cen, "STOMACH  (gas-filled lumen)", 92, 34)
    t.arrow(*top, "cardia / EGJ", -84, -46)
    ls = lun[k0:k1, j, i0:i1]
    if ls.any():
        rr2, cc2 = np.where(ls)
        sel = np.abs(cc2 - top[0]) < 40
        if sel.any():
            t.arrow(cc2[sel].mean(), rr2[sel].max(), "left hemidiaphragm\n(lung base above)",
                    -86, -40)
    t.corner("patient RIGHT", "patient LEFT")
    out.append(t.finish())

    # sagittal through the gastric centroid
    i = I(xcen)
    k0, k1, j0, j1 = K(-345), K(-500), J(-255), J(-95)
    t = Tile(ctwin(V[k0:k1, j0:j1, i]), sto[k0:k1, j0:j1, i], sy, sz,
             "CT  SAGITTAL", f"x = {xcen:.0f} mm  (through the stomach)")
    cen, top = anchors(sto[k0:k1, j0:j1, i])
    t.arrow(*cen, "STOMACH", 86, 40)
    t.arrow(*top, "cardia / EGJ\n(hiatus level)", 92, -46)
    t.corner("anterior", "posterior")
    out.append(t.finish())

    # axial at the top of the stomach = hiatus level
    k = K(ztop_st) + 3
    j0, j1, i0, i1 = J(-258), J(-70), I(-105), I(160)
    t = Tile(ctwin(V[k, j0:j1, i0:i1]), sto[k, j0:j1, i0:i1], sx, sy,
             "CT  AXIAL", f"z = {ztop_st - 3 * sz:.0f} mm  (hiatus / cardia level)")
    a = anchors(sto[k, j0:j1, i0:i1])[0]
    if a:
        t.arrow(*a, "STOMACH at the hiatus", 86, 44)
    t.corner("patient RIGHT", "patient LEFT")
    out.append(t.finish())
    return out


# ------------------------------------------------------------------ MR
def load(n, axis):
    ms = []
    for f in os.listdir(ROOT):
        p = os.path.join(ROOT, f)
        try:
            d = pydicom.dcmread(p, stop_before_pixels=True)
        except Exception:
            continue
        if int(d.get("SeriesNumber") or 0) == n:
            ms.append((d, p))
    ms.sort(key=lambda t: float(t[0].ImagePositionPatient[axis]))
    return ms


def gas_blob(a, box):
    """Largest dark (gas) blob strictly inside the search box."""
    r0, r1, c0, c1 = box
    r0, c0 = max(r0, 0), max(c0, 0)
    sub = a[r0:r1, c0:c1]
    if sub.size == 0:
        return np.zeros_like(a, bool), 0
    m = sub < np.percentile(sub, 20)
    m = ndi.binary_opening(m, np.ones((3, 3)), iterations=2)
    lab, n = ndi.label(m)
    best, bsz = None, 0
    for cid in range(1, n + 1):
        c = lab == cid
        if c.sum() < 60:
            continue
        rr, cc = np.where(c)
        if rr.min() == 0 or cc.min() == 0 or rr.max() == c.shape[0] - 1 \
           or cc.max() == c.shape[1] - 1:
            continue                                    # touches the box edge
        if c.sum() > bsz:
            best, bsz = c, c.sum()
    full = np.zeros_like(a, bool)
    if best is not None:
        full[r0:r1, c0:c1] = ndi.binary_closing(best, np.ones((3, 3)), iterations=2)
    return full, bsz


def pick_slice(items, boxfn):
    """Choose the slice with the biggest valid gastric gas blob."""
    best = None
    for idx, a, meta in items:
        m, s = gas_blob(a, boxfn(meta))
        if best is None or s > best[0]:
            best = (s, idx, a, m, meta)
    return best


def mr_tiles():
    out = []

    # ---- T2 HASTE coronal ----
    ms = load(2, 1)
    items = []
    for idx, (d, p) in enumerate(ms):
        a = norm(pydicom.dcmread(p).pixel_array)
        items.append((idx, a, d))
    def boxc(d):
        ps = float(d.PixelSpacing[0])
        xo, zo = float(d.ImagePositionPatient[0]), float(d.ImagePositionPatient[2])
        return (int((zo - 160) / ps), int((zo - 10) / ps),
                int((5 - xo) / ps), int((140 - xo) / ps))
    s, idx, a, m, d0 = pick_slice(items, boxc)
    ps = float(d0.PixelSpacing[0])
    print(f"MR T2 coronal: slice {idx}  y={float(d0.ImagePositionPatient[1]):.0f}  blob={s}")
    t = Tile(a, m, ps, ps, "MR  T2 HASTE  CORONAL",
             f"y = {float(d0.ImagePositionPatient[1]):.0f} mm   (fluid bright, gas black)")
    cen, top = anchors(m)
    if cen:
        t.arrow(*cen, "STOMACH", 92, 40)
        t.arrow(*top, "cardia / EGJ", -84, -44)
    t.corner("patient RIGHT", "patient LEFT")
    out.append(t.finish())

    # ---- T2 HASTE sagittal ----
    ms = load(3, 0)
    items = []
    for idx, (d, p) in enumerate(ms):
        x = float(d.ImagePositionPatient[0])
        if not (5 < x < 120):
            continue
        items.append((idx, norm(pydicom.dcmread(p).pixel_array), d))
    def boxs(d):
        ps = float(d.PixelSpacing[0])
        yo, zo = float(d.ImagePositionPatient[1]), float(d.ImagePositionPatient[2])
        return (int((zo - 160) / ps), int((zo - 10) / ps),
                int((-70 - yo) / ps), int((45 - yo) / ps))
    s, idx, a, m, d0 = pick_slice(items, boxs)
    ps = float(d0.PixelSpacing[0])
    print(f"MR T2 sagittal: slice {idx}  x={float(d0.ImagePositionPatient[0]):.0f}  blob={s}")
    t = Tile(a, m, ps, ps, "MR  T2 HASTE  SAGITTAL",
             f"x = {float(d0.ImagePositionPatient[0]):.0f} mm  (through the stomach)")
    cen, top = anchors(m)
    if cen:
        t.arrow(*cen, "STOMACH", 90, 42)
        t.arrow(*top, "cardia / EGJ\n(hiatus level)", 92, -46)
    t.corner("anterior", "posterior")
    out.append(t.finish())

    # ---- VIBE Dixon water coronal (the 3-D MR series) ----
    M = np.load(f"{SP}/mr_vibe.npy")
    mg = pickle.load(open(f"{SP}/mr_geo.pkl", "rb"))
    msz, msy, msx = mg["sz"], mg["sy"], mg["sx"]
    zo, xo, yo = mg["z_top"], mg["x0"], mg["y0"]
    box = (int((zo - 160) / msz), int((zo - 10) / msz),
           int((5 - xo) / msx), int((140 - xo) / msx))
    best = None
    jmax = int((30 - yo) / msy)
    for j in range(min(jmax, M.shape[1])):
        a = norm(M[:, j, :])
        m, s = gas_blob(a, box)
        if best is None or s > best[0]:
            best = (s, j, a, m)
    s, j, a, m = best
    print(f"MR VIBE coronal: slice {j}  y={yo + j * msy:.0f}  blob={s}")
    t = Tile(a, m, msx, msz, "MR  T1 VIBE DIXON (water)  CORONAL",
             f"y = {yo + j * msy:.0f} mm   3-D, 1.6 mm - the MR volume used for 3-D")
    cen, top = anchors(m)
    if cen:
        t.arrow(*cen, "STOMACH", 92, 40)
    t.corner("patient RIGHT", "patient LEFT")
    out.append(t.finish())
    return out


if __name__ == "__main__":
    tiles = ct_tiles() + mr_tiles()
    sheet = Image.new("RGB", (TILE[0] * 3, TILE[1] * 2 + 40), (6, 6, 8))
    for i, t in enumerate(tiles):
        sheet.paste(t, ((i % 3) * TILE[0], (i // 3) * TILE[1] + 40))
    d = ImageDraw.Draw(sheet)
    d.text((12, 8), "STOMACH AND OESOPHAGEAL HIATUS   -   CT (top row) and MR (bottom row)   "
                    "-   cyan = segmented gastric lumen   -   abdomen, 2026-07-22",
           fill=CY, font=F)
    d.text((12, 26), "Radiological convention: patient LEFT is on the viewer's RIGHT. "
                     "Labels are anatomical orientation only, not a radiological report.",
           fill=(170, 170, 170), font=FS)
    sheet.save(f"{SP}/FIG_hiatus_panel.png")
    print("saved", sheet.size)
