"""Tests para draw_join_graph_figure (rasteriza el join graph, grupo eda).

Usa el backend Agg sin abrir ventanas; cada test cierra la Figure construida
(matplotlib.pyplot.close) para no acumular estado entre tests. Las aserciones de
guardado escriben a tmp_path (fixture de pytest) y comprueban que el PNG no está
vacío.
"""

import matplotlib

matplotlib.use("Agg")

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

from draw_join_graph_figure import draw_join_graph_figure


def _make_join_graph():
    """Join graph mínimo: 3 nodos (customers/orders/products) y 2 aristas.

    orders -> customers y orders -> products. `orders` es el hub (out_degree 2).
    """
    return {
        "nodes": [
            {"table": "customers", "out_degree": 0, "in_degree": 1, "role": "dimension"},
            {"table": "orders", "out_degree": 2, "in_degree": 0, "role": "fact"},
            {"table": "products", "out_degree": 0, "in_degree": 1, "role": "dimension"},
        ],
        "edges": [
            {
                "from_table": "orders",
                "from_col": "customer_id",
                "to_table": "customers",
                "to_col": "id",
                "cardinality": "N:1",
                "inclusion": 1.0,
            },
            {
                "from_table": "orders",
                "from_col": "product_id",
                "to_table": "products",
                "to_col": "id",
                "cardinality": "N:1",
                "inclusion": 0.98,
            },
        ],
        "hubs": ["orders"],
    }


def test_returns_figure_with_axis():
    fig = draw_join_graph_figure(_make_join_graph(), title="Relaciones FK")
    assert isinstance(fig, Figure)
    # Al menos un eje con el diagrama.
    assert len(fig.axes) >= 1
    plt.close(fig)


def test_savefig_produces_nonempty_png(tmp_path):
    fig = draw_join_graph_figure(_make_join_graph())
    out = tmp_path / "g.png"
    fig.savefig(out)
    assert out.exists()
    assert out.stat().st_size > 0
    plt.close(fig)


def test_empty_dict_does_not_raise_and_savefig_png(tmp_path):
    fig = draw_join_graph_figure({})
    assert isinstance(fig, Figure)
    out = tmp_path / "empty.png"
    fig.savefig(out)
    assert out.stat().st_size > 0
    plt.close(fig)


def test_none_does_not_raise_and_savefig_png(tmp_path):
    fig = draw_join_graph_figure(None)
    assert isinstance(fig, Figure)
    out = tmp_path / "none.png"
    fig.savefig(out)
    assert out.stat().st_size > 0
    plt.close(fig)
