"""Tests for surgical-plan save/load (JSON persistence)."""
import numpy as np
from sulcora.planning import Trajectory
from sulcora.plan import SurgicalPlan, save_plan, load_plan


def test_plan_roundtrip(tmp_path):
    plan = SurgicalPlan(patient_id="CASE-42", note="bilateral DBS")
    plan.add("Left lead", Trajectory((10, 0, 10), (2, 0, 2)),
             risk={"nearest": "Left Thalamus", "min_clearance_mm": 4.2, "band": "CAUTION",
                   "per_structure": {"vessels": {"clearance_mm": 4.2, "band": "CAUTION"}}})
    plan.add("Right lead", Trajectory((-10, 0, 10), (-2, 0, 2)))
    p = str(tmp_path / "plan.json")
    save_plan(plan, p)
    back = load_plan(p)
    assert back.patient_id == "CASE-42" and back.note == "bilateral DBS"
    assert len(back) == 2
    assert [it.name for it in back] == ["Left lead", "Right lead"]
    assert np.allclose(back.items[0].trajectory.entry, [10, 0, 10])
    assert np.allclose(back.items[0].trajectory.target, [2, 0, 2])
    assert back.items[0].risk["min_clearance_mm"] == 4.2
    assert back.items[0].risk["per_structure"]["vessels"]["band"] == "CAUTION"
    assert back.items[1].risk is None


def test_plan_roundtrip_sanitizes_numpy(tmp_path):
    plan = SurgicalPlan(patient_id="CASE-1")
    plan.add("t", Trajectory(np.array([1.0, 2, 3]), np.array([4.0, 5, 6])),
             risk={"clearance_mm": np.float64(3.5), "pts": np.array([1.0, 2.0])})
    p = str(tmp_path / "p.json")
    save_plan(plan, p)                          # must not raise on numpy types
    back = load_plan(p)
    assert back.items[0].risk["clearance_mm"] == 3.5
    assert back.items[0].risk["pts"] == [1.0, 2.0]
