"""Tests for src/pygui/backend/cluster_average.py."""
import math

from pygui.backend.cluster_average import average_clusters, group_sensors_by_radius
from pygui.backend.wafer.zwafer_models import Sensor


def test_members_take_cluster_mean():
    vals = [10.0, 20.0, 100.0, 0.0]
    clusters = [[0, 1], [2, 3]]
    assert average_clusters(vals, clusters) == [15.0, 15.0, 50.0, 50.0]


def test_unclustered_sensors_unchanged():
    vals = [10.0, 20.0, 30.0]
    assert average_clusters(vals, [[0, 1]]) == [15.0, 15.0, 30.0]


def test_empty_clusters_is_identity():
    assert average_clusters([1.0, 2.0], []) == [1.0, 2.0]


def test_nan_handling_in_averaging():
    vals = [10.0, float('nan'), 100.0, float('nan')]
    clusters = [[0, 1], [2, 3]]
    res = average_clusters(vals, clusters)
    assert res[0] == 10.0
    assert res[1] == 10.0
    assert res[2] == 100.0
    assert res[3] == 100.0


def test_all_nan_cluster():
    vals = [float('nan'), float('nan'), 5.0]
    clusters = [[0, 1]]
    res = average_clusters(vals, clusters)
    assert math.isnan(res[0])
    assert math.isnan(res[1])
    assert res[2] == 5.0


def test_group_by_radius():
    sensors = [
        Sensor(label="1", x=0.0, y=0.0),      # center (r=0)
        Sensor(label="2", x=10.0, y=0.0),     # r=10
        Sensor(label="3", x=0.0, y=10.5),     # r=10.5 (within 2mm)
        Sensor(label="4", x=20.0, y=0.0),     # r=20
    ]
    # Center should be excluded or not grouped; other sensors grouped
    clusters = group_sensors_by_radius(sensors, tolerance=2.0)
    # Expected: 2 and 3 are in the same cluster because 10.5 - 10.0 <= 2.0.
    assert [1, 2] in clusters
