"""Tests for CT support: HU windowing, modality detection, tissue segmentation."""
import numpy as np
from sulcora.volume import Volume
from sulcora import ct as C


def _head_ct(shape=(40, 40, 40)):
    """Synthetic head CT: air ~-1000, skull ring ~1000 HU, brain ~35 HU,
    a central CSF/ventricle ~5 HU."""
    ii, jj, kk = np.meshgrid(np.arange(shape[0]), np.arange(shape[1]), np.arange(shape[2]), indexing="ij")
    c = np.array(shape) / 2
    r = np.sqrt(((ii - c[0])) ** 2 + ((jj - c[1])) ** 2 + ((kk - c[2])) ** 2)
    d = np.full(shape, -1000.0, np.float32)          # air
    d[r <= 18] = 35.0                                # brain
    d[(r > 16) & (r <= 18)] = 1000.0                 # skull shell
    d[r <= 4] = 5.0                                  # central CSF
    return Volume(d, np.eye(4))


def test_apply_window_maps_level_and_edges():
    vol = Volume(np.array([[[0, 40, 80]]], np.float32), np.eye(4))  # HU 0,40,80
    w = C.apply_window(vol, level=40, width=80)                     # lo=0, hi=80
    assert w.data[0, 0, 0] == 0                                     # HU 0 -> 0
    assert abs(int(w.data[0, 0, 1]) - 127) <= 2                     # HU 40 -> mid
    assert w.data[0, 0, 2] == 255                                   # HU 80 -> 255
    assert w.data.dtype == np.uint8


def test_window_preset_and_unknown():
    vol = _head_ct()
    for name in ("brain", "blood", "bone", "stroke", "subdural"):
        w = C.window_preset(vol, name)
        assert w.data.dtype == np.uint8 and w.shape == vol.shape
    import pytest
    with pytest.raises(ValueError):
        C.window_preset(vol, "bogus")


def test_is_ct_by_hu_range_and_metadata():
    assert C.is_ct(_head_ct()) is True                             # air + bone present
    mri = Volume((np.random.default_rng(0).random((10, 10, 10)) * 500).astype(np.float32), np.eye(4))
    assert C.is_ct(mri) is False                                   # all positive, no bone/air
    # metadata override wins
    tagged = Volume(np.zeros((5, 5, 5), np.float32), np.eye(4), meta={"modality": "CT"})
    assert C.is_ct(tagged) is True


def test_skull_and_brain_and_csf_masks():
    vol = _head_ct()
    skull = C.skull_mask(vol)
    assert int(skull.data.sum()) > 0
    c = np.array(vol.shape) // 2
    assert skull.data[c[0], c[1], c[2]] == 0                       # centre is not bone
    brain = C.brain_mask(vol)
    assert brain.data[c[0], c[1], c[2]] == 1                       # centre is brain (holes filled)
    assert brain.data[0, 0, 0] == 0                                # air excluded
    # brain excludes the bone shell
    assert int((np.asarray(brain.data) & np.asarray(skull.data)).sum()) == 0
    csf = C.csf_mask(vol)
    assert csf.data[c[0], c[1], c[2]] == 1                         # central CSF picked up


def test_segment_hu_generic_keep_largest():
    vol = _head_ct()
    blood = C.segment_hu(vol, 45, 100, keep_largest=True)          # nothing in 45-100 here
    assert set(np.unique(blood.data)).issubset({0, 1})
