"""Tests para relationship_scatter_figure (scatter de un par numérico, grupo eda).

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

import os
import sys

sys.path.insert(0, os.path.dirname(__file__))

import matplotlib

matplotlib.use("Agg")

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

from relationship_scatter_figure import relationship_scatter_figure


def _scatter_offsets(fig):
    """Return the plotted points of the first PathCollection (scatter) found."""
    for ax in fig.axes:
        for coll in ax.collections:
            if isinstance(coll, PathCollection):
                return coll.get_offsets()
    return None


def test_returns_figure():
    xs = [float(i) for i in range(20)]
    ys = [2.0 * x + 1.0 for x in xs]  # y = 2x + 1
    classification = {
        "tipo": "lineal",
        "pearson": 1.0,
        "r2_linear": 1.0,
        "spearman": 1.0,
        "r2_poly2": 1.0,
        "r2_poly3": 1.0,
        "best_degree": 1,
        "coeffs": [2.0, 1.0],
    }
    fig = relationship_scatter_figure(
        xs, ys, x_label="a", y_label="b", classification=classification
    )
    assert hasattr(fig, "savefig")
    assert len(fig.axes) >= 1
    plt.close(fig)


def test_downsample_determinista():
    n = 5000
    xs = [float(i) for i in range(n)]
    ys = [0.5 * x for x in xs]
    classification = {
        "tipo": "lineal",
        "pearson": 1.0,
        "r2_linear": 1.0,
        "spearman": 1.0,
        "r2_poly2": 1.0,
        "r2_poly3": 1.0,
        "best_degree": 1,
        "coeffs": [0.5, 0.0],
    }
    fig = relationship_scatter_figure(
        xs, ys, x_label="x", y_label="y", classification=classification, max_points=1000
    )
    assert isinstance(fig, Figure)
    offsets = _scatter_offsets(fig)
    assert offsets is not None
    # El nº de puntos dibujados no debe exceder el cap.
    assert len(offsets) <= 1000
    plt.close(fig)


def test_empty_no_lanza():
    fig = relationship_scatter_figure([], [], x_label="x", y_label="y")
    assert isinstance(fig, Figure)
    plt.close(fig)


def test_classification_none():
    # Solo se ejecuta si el módulo hermano classify_relationship_type existe.
    try:
        import classify_relationship_type  # noqa: F401
    except Exception:
        import pytest

        pytest.skip("classify_relationship_type aún no disponible")
    xs = [float(i) for i in range(30)]
    ys = [3.0 * x - 2.0 for x in xs]
    fig = relationship_scatter_figure(
        xs, ys, x_label="a", y_label="b", classification=None
    )
    assert isinstance(fig, Figure)
    assert len(fig.axes) >= 1
    plt.close(fig)
