"""Probe's-eye and in-line trajectory reformats — the views surgeons plan in.

Renders, for a planned trajectory on the real reference MRI: the in-line view
(the plane containing the whole entry→target path) and the probe's-eye view
(the cross-section perpendicular to the trajectory at the target).

RESEARCH SOFTWARE — NOT FOR CLINICAL USE.
"""
import os, sys
import numpy as np
import matplotlib; matplotlib.use("Agg")
import matplotlib.pyplot as plt

HERE = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, HERE)
from sulcora.io import load
from sulcora.planning import Trajectory
from sulcora import reslice as R

DOCS = os.path.join(HERE, "docs", "images"); os.makedirs(DOCS, exist_ok=True)
nii = os.path.join(HERE, "sample_data", "mni152_t1_2mm.nii.gz")
if not os.path.exists(nii):
    import nibabel as nib
    from nilearn.datasets import load_mni152_template
    nib.save(load_mni152_template(resolution=2), nii)

vol = load(nii)
ni, nj, nk = vol.shape
target = vol.voxel_to_world((ni // 2 + 3, nj // 2, nk // 2))
entry = vol.voxel_to_world((int(ni * 0.72), int(nj * 0.60), int(nk * 0.92)))
traj = Trajectory(entry, target)
print(f"trajectory length={traj.length:.1f}mm angle={traj.angle_from_axis():.0f}deg")

inl, us = R.along_trajectory(vol, traj, width_mm=60.0, pad_mm=12.0, spacing_mm=1.0)
eye = R.probes_eye(vol, traj, depth_mm=None, fov_mm=50.0, spacing_mm=0.6)

# standard axial MPR for reference
disp = vol.window().data
tv = np.round(vol.world_to_voxel(target)).astype(int)
ev = np.round(vol.world_to_voxel(entry)).astype(int)

fig, ax = plt.subplots(1, 3, figsize=(14, 5), facecolor="#0b0f18")
ax[0].imshow(disp[:, :, int(tv[2])].T, cmap="gray", origin="lower")
ax[0].plot([ev[0], tv[0]], [ev[1], tv[1]], "-", color="#39c0ff", lw=2)
ax[0].plot(ev[0], ev[1], "o", color="#39ff9e", ms=6); ax[0].plot(tv[0], tv[1], "o", color="#ff5d5d", ms=6)
ax[0].set_title("Axis-aligned axial (reference)", color="#9fd0ff", fontsize=11); ax[0].axis("off")

# in-line view: rows = perpendicular, cols = along path; mark entry/target columns
ax[1].imshow(inl, cmap="gray", origin="lower", aspect="auto")
i0 = int(np.argmin(np.abs(us - 0.0))); iL = int(np.argmin(np.abs(us - traj.length)))
cy = inl.shape[0] // 2
ax[1].plot([i0, iL], [cy, cy], "-", color="#f5b041", lw=2.2)
ax[1].plot(i0, cy, "o", color="#39ff9e", ms=6); ax[1].plot(iL, cy, "o", color="#ff5d5d", ms=6)
ax[1].set_title("In-line view (plane of the trajectory)", color="#9fd0ff", fontsize=11); ax[1].axis("off")

ax[2].imshow(eye, cmap="gray", origin="lower")
c = eye.shape[0] // 2
ax[2].plot(c, c, "+", color="#ff5d5d", ms=14, mew=2)
ax[2].set_title("Probe's-eye (perpendicular at target)", color="#9fd0ff", fontsize=11); ax[2].axis("off")

fig.suptitle("Probe-aligned reformats — the views surgeons plan trajectories in", color="#dce6f5", fontsize=13)
fig.text(0.5, 0.02, "In-line = whole entry→target path in one plane · probe's-eye = cross-section the tip faces. "
         "RESEARCH SOFTWARE — NOT FOR CLINICAL USE.", color="#c0392b", ha="center", fontsize=9)
fig.tight_layout(rect=[0, 0.05, 1, 0.94])
out = os.path.join(DOCS, "probes_eye.png")
fig.savefig(out, dpi=130, facecolor=fig.get_facecolor()); plt.close(fig)
print("wrote", out, "\nPROBES-EYE PROOF OK")
