"""Tests para missingness_rank_bar_figure (barras de % faltante, 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_rank_bar_figure import missingness_rank_bar_figure


def test_returns_figure_with_axes():
    names = ["edad", "ingresos", "ciudad"]
    pcts = [12.5, 40.0, 3.2]
    fig = missingness_rank_bar_figure(names, pcts, title="faltantes")
    assert isinstance(fig, Figure)
    assert len(fig.axes) >= 1
    plt.close(fig)


def test_sorted_descending_largest_on_top():
    names = ["a", "b", "c"]
    pcts = [10.0, 50.0, 25.0]
    fig = missingness_rank_bar_figure(names, pcts)
    ax = fig.axes[0]
    # barh dibuja de abajo arriba; la mayor (50, "b") debe quedar arriba (mayor y).
    bars = ax.patches
    # El último parche (mayor índice y) corresponde a la barra superior.
    widths = [b.get_width() for b in bars]
    assert max(widths) == 50.0
    # La barra con la mayor anchura es la de mayor coordenada y (arriba).
    top_bar = max(bars, key=lambda b: b.get_y())
    assert top_bar.get_width() == 50.0
    plt.close(fig)


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


def test_xlim_is_zero_to_hundred():
    fig = missingness_rank_bar_figure(["a"], [42.0])
    ax = fig.axes[0]
    assert ax.get_xlim() == (0.0, 100.0)
    plt.close(fig)


def test_length_mismatch_and_non_numeric_are_handled():
    # Más names que pcts + un pct None -> zip recorta y None se coacciona a 0.
    names = ["a", "b", "c"]
    pcts = [None, 30.0]
    fig = missingness_rank_bar_figure(names, pcts)
    assert isinstance(fig, Figure)
    assert len(fig.axes) >= 1
    plt.close(fig)
