"""Tests para missingness_corr_heatmap_figure (heatmap de ausencias, grupo eda).

Usa el backend Agg sin pyplot; no muestra ni guarda figuras. Cada test cierra
explícitamente la Figure construida (matplotlib.pyplot.close) para no acumular
estado entre tests.
"""

import matplotlib

matplotlib.use("Agg")

import matplotlib.pyplot as plt  # noqa: E402
from matplotlib.figure import Figure  # noqa: E402

from missingness_corr_heatmap_figure import missingness_corr_heatmap_figure


def _identity_matrix(n):
    """Matriz NxN con diagonal 1.0 y resto 0.0 (correlación de ausencias)."""
    return [[1.0 if i == j else 0.0 for j in range(n)] for i in range(n)]


def test_returns_figure_with_axes():
    matrix = [[1.0, 0.3, -0.2], [0.3, 1.0, 0.5], [-0.2, 0.5, 1.0]]
    labels = ["edad", "ingresos", "ciudad"]
    fig = missingness_corr_heatmap_figure(matrix, labels, title="ausencias")
    assert isinstance(fig, Figure)
    # Heatmap (>=1 axes) + colorbar añade su propio Axes -> al menos 1.
    assert len(fig.axes) >= 1
    plt.close(fig)


def test_empty_matrix_does_not_raise_and_returns_figure():
    fig = missingness_corr_heatmap_figure([], [], title="vacía")
    assert isinstance(fig, Figure)
    assert len(fig.axes) >= 1
    plt.close(fig)


def test_empty_labels_returns_message_figure():
    fig = missingness_corr_heatmap_figure([[1.0]], [], title="sin labels")
    assert isinstance(fig, Figure)
    plt.close(fig)


def test_large_matrix_omits_annotations():
    n = 16
    fig = missingness_corr_heatmap_figure(
        _identity_matrix(n), [f"col_{i}" for i in range(n)]
    )
    assert isinstance(fig, Figure)
    assert len(fig.axes) >= 1
    plt.close(fig)


def test_ragged_and_non_numeric_cells_are_handled():
    # Fila corta + celda None + celda string -> se rellenan/coercen sin lanzar.
    matrix = [[1.0, None], ["x", 1.0, 0.5]]
    labels = ["a", "b"]
    fig = missingness_corr_heatmap_figure(matrix, labels)
    assert isinstance(fig, Figure)
    plt.close(fig)
