"""Build a multi-trajectory (bilateral) surgical-plan PDF report on real MRI."""
import os, sys
import numpy as np
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.deformation import ProbeDeformation
from sulcora.plan import SurgicalPlan
from sulcora.report import build_report
from sulcora import atlas as A
from sulcora import risk as R

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)
cort, clabels = A.load_harvard_oxford("cort-maxprob-thr25-2mm")
cort = A.resample_atlas_to(cort, vol)
elo = [l for l in A.ELOQUENT_DEFAULT if l in clabels]
ni, nj, nk = vol.shape

# bilateral deep targets (left/right), frontal entries — like bilateral DBS leads
plan = SurgicalPlan(patient_id="DEMO-CASE-001", note="Bilateral deep targets")
for side, xoff in [("Left lead", -8), ("Right lead", +8)]:
    tw = vol.voxel_to_world((ni // 2 + xoff // 2, nj // 2, nk // 2))
    ew = vol.voxel_to_world((ni // 2 + int(xoff * 1.6), int(nj * 0.62), int(nk * 0.92)))
    traj = Trajectory(ew, tw)
    pd = ProbeDeformation(traj, probe_radius_mm=2.0, influence_radius_mm=20.0)
    rep = R.deformation_aware_risk(traj, cort, clabels, names=elo, deformation=pd, n=80)
    plan.add(side, traj, risk=rep)

out = os.path.join(HERE, "docs", "Sulcora_Plan_Report.pdf")
build_report(plan, vol, out, title="Sulcora Surgical Plan")
print("wrote", out, os.path.getsize(out) // 1024, "KB")
print("PLAN REPORT OK")
