"""Generate the rich exported plan report (what the neurosurgeon exports).

Builds a plan on a phantom with vessels + eloquent structures and writes the
multi-page PDF: per-structure clearance table (static + deformation-aware),
clearance-vs-depth profile, and probe-aligned reformats.

RESEARCH SOFTWARE — NOT FOR CLINICAL USE.
"""
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.volume import Volume
from sulcora import vessels as V, session
from sulcora.optimizer import RiskStructure
from sulcora.plan import SurgicalPlan
from sulcora.report import build_report


def main():
    docs = os.path.join(HERE, "docs", "images"); os.makedirs(docs, exist_ok=True)
    shape = (90, 90, 90); ni, nj, nk = shape
    ii, jj, kk = np.meshgrid(np.arange(ni), np.arange(nj), np.arange(nk), indexing="ij")
    c = np.array(shape) / 2
    ell = ((ii - c[0]) / (0.46 * ni)) ** 2 + ((jj - c[1]) / (0.44 * nj)) ** 2 + ((kk - c[2]) / (0.46 * nk)) ** 2
    brain = (40.0 / (1.0 + np.exp((ell - 1.0) / 0.04))).astype(np.float32)
    def tube(p0, p1, r, val):
        p0, p1 = np.asarray(p0, float), np.asarray(p1, float)
        for t in np.linspace(0, 1, 120):
            cc = p0 + t * (p1 - p0)
            m = (ii - cc[0]) ** 2 + (jj - cc[1]) ** 2 + (kk - cc[2]) ** 2 <= r * r
            brain[m] = val
    tube([45, 22, 32], [44, 60, 60], 2.2, 230); tube([44, 42, 46], [64, 56, 36], 1.6, 220)
    brain = np.clip(brain + np.random.default_rng(0).normal(0, 3, shape), 0, None).astype(np.float32)
    vol = Volume(brain, np.eye(4)); interior = ell <= 1.0
    vmask = V.vessel_mask(vol, scales=(1.0, 2.0, 3.0), percentile=99.3)
    vmask = Volume((np.asarray(vmask.data) & interior).astype(np.uint8), vmask.affine)
    elo = (((ii - 60) ** 2 + (jj - 46) ** 2 + (kk - 70) ** 2) <= 9 ** 2).astype(np.uint8)
    structures = [RiskStructure("vessels", vmask, 3.0, 1.5),
                  RiskStructure("eloquent", Volume(elo, np.eye(4)), 3.0, 1.0)]

    target = np.array([45.0, 38.0, 26.0])
    plans = [p for p in session.recommend(vol, target, structures, max_angle_deg=60,
                                          n_theta=9, n_phi=26) if p.feasible][:2]
    plan = SurgicalPlan(patient_id="DEMO-CASE-001", note="phantom demonstration")
    for i, p in enumerate(plans):
        plan.add(f"Corridor #{i+1}", p.trajectory)

    out = os.path.join(docs, "plan_report.pdf")
    build_report(plan, vol, out, title="Sulcora Surgical Plan", structures=structures)
    print("wrote", out, f"({os.path.getsize(out)} bytes, {len(plan)+1} pages)")
    print("REPORT PROOF OK")


if __name__ == "__main__":
    import multiprocessing as mp; mp.freeze_support(); main()
