import io

import pandas as pd

from mnemosynecore import viz


class _FakeAx:
    def plot(self, *args, **kwargs):
        return None

    def legend(self, *args, **kwargs):
        return None

    def set_title(self, *args, **kwargs):
        return None

    def set_xlabel(self, *args, **kwargs):
        return None

    def grid(self, *args, **kwargs):
        return None

    def imshow(self, *args, **kwargs):
        return object()

    def set_xticks(self, *args, **kwargs):
        return None

    def set_xticklabels(self, *args, **kwargs):
        return None

    def set_yticks(self, *args, **kwargs):
        return None

    def set_yticklabels(self, *args, **kwargs):
        return None

    def text(self, *args, **kwargs):
        return None


class _FakeFig:
    def savefig(self, buffer, format=None, bbox_inches=None, dpi=None):
        if isinstance(buffer, io.BytesIO):
            buffer.write(b"PNG")

    def autofmt_xdate(self):
        return None

    def tight_layout(self):
        return None

    def colorbar(self, *args, **kwargs):
        return None


class _FakePlt:
    def __init__(self):
        self.fig = _FakeFig()
        self.ax = _FakeAx()

    def subplots(self, figsize=None):
        return self.fig, self.ax

    def close(self, fig):
        return None


def test_plot_line_png(monkeypatch):
    monkeypatch.setattr(viz, "_require_matplotlib", lambda: _FakePlt())
    df = pd.DataFrame([{"dt": "2026-03-01", "value": 10}, {"dt": "2026-03-02", "value": 12}])
    out = viz.plot_line_png(df=df, x="dt", y="value", title="line")
    assert out.startswith(b"PNG")


def test_plot_bar_png(monkeypatch):
    monkeypatch.setattr(viz, "_require_matplotlib", lambda: _FakePlt())
    monkeypatch.setattr(
        pd.DataFrame,
        "plot",
        lambda self, kind=None, ax=None, stacked=None: None,
    )
    df = pd.DataFrame([{"metric": "a", "value": 10}, {"metric": "b", "value": 20}])
    out = viz.plot_bar_png(df=df, x="metric", y="value", title="bar")
    assert out.startswith(b"PNG")


def test_plot_heatmap_png(monkeypatch):
    monkeypatch.setattr(viz, "_require_matplotlib", lambda: _FakePlt())
    df = pd.DataFrame([{"m1": 1, "m2": 2}, {"m1": 3, "m2": 4}])
    out = viz.plot_heatmap_png(df=df, title="heat")
    assert out.startswith(b"PNG")


def test_send_plot(monkeypatch):
    captured = {}
    monkeypatch.setattr(
        viz,
        "send_file_bytes",
        lambda **kwargs: captured.update(kwargs) or {"file_id": "F1"},
    )
    out = viz.send_plot(
        channel_id="CH",
        bot_id="BOT",
        png_bytes=b"PNG",
        file_name="x.png",
    )
    assert out["file_id"] == "F1"
    assert captured["mime_type"] == "image/png"
