import types

from tidyfit.eval_viz import (
    confusion_matrix_data,
    roc_curve_data,
    pr_curve_data,
    maybe_plot_curve,
    save_curve_plot,
)


def test_confusion_matrix_data():
    cm = confusion_matrix_data([0, 0, 1, 1], [0, 1, 0, 1])
    assert cm.shape == (2, 2)
    assert cm.sum() == 4


def test_roc_pr_curve_data():
    y = [0, 1, 1, 0, 1]
    s = [0.1, 0.8, 0.7, 0.3, 0.9]
    roc = roc_curve_data(y, s, thresholds=[0.2, 0.5, 0.8])
    pr = pr_curve_data(y, s, thresholds=[0.2, 0.5, 0.8])
    assert len(roc) == 3
    assert len(pr) == 3


def test_plot_helpers_with_fake_matplotlib(monkeypatch, tmp_path):
    fake = types.ModuleType("matplotlib.pyplot")
    fake.figure = lambda: None
    fake.plot = lambda x, y: None
    fake.xlabel = lambda x: None
    fake.ylabel = lambda y: None
    fake.title = lambda t: None
    fake.tight_layout = lambda: None
    fake.close = lambda: None
    fake.savefig = lambda p: open(p, "wb").write(b"ok")

    import sys

    fake_pkg = types.ModuleType("matplotlib")
    fake_pkg.pyplot = fake
    monkeypatch.setitem(sys.modules, "matplotlib", fake_pkg)
    monkeypatch.setitem(sys.modules, "matplotlib.pyplot", fake)

    pts = [(0.2, 0.1, 0.8), (0.5, 0.2, 0.7)]
    assert maybe_plot_curve(pts, "x", "y", "t") is True
    out = tmp_path / "roc.png"
    assert save_curve_plot(pts, "x", "y", "t", out) is True
    assert out.exists()
