# retoor <retoor@molodetz.nl>

from devplacepy.services.bot.monitor import BotMonitor, BotFrame


def test_update_meta_creates_and_merges():
    monitor = BotMonitor()
    monitor.update_meta(0, username="bytewren", persona="grumpy_senior")
    monitor.update_meta(0, action="POST: rant [1]")
    frame = monitor.frames[0]
    assert frame.username == "bytewren"
    assert frame.persona == "grumpy_senior"
    assert frame.action == "POST: rant [1]"
    assert frame.label() == "bytewren"


def test_store_and_read_image(tmp_path, monkeypatch):
    import devplacepy.services.bot.monitor as mod

    monkeypatch.setattr(mod, "MONITOR_DIR", tmp_path)
    monitor = BotMonitor()
    monitor.update_meta(2, username="anon")
    monitor.store_image(2, b"jpegbytes")
    assert monitor.frames[2].has_image is True
    assert monitor.read_image(2) == b"jpegbytes"
    assert monitor.frame_path(2) == tmp_path / "slot2.jpg"


def test_store_image_overwrites(tmp_path, monkeypatch):
    import devplacepy.services.bot.monitor as mod

    monkeypatch.setattr(mod, "MONITOR_DIR", tmp_path)
    monitor = BotMonitor()
    monitor.store_image(4, b"first")
    captured_first = monitor.frames[4].captured_at
    monitor.store_image(4, b"second")
    assert monitor.read_image(4) == b"second"
    assert monitor.frames[4].captured_at >= captured_first
    assert len(list(tmp_path.glob("slot4.jpg"))) == 1


def test_store_empty_image_is_noop(tmp_path, monkeypatch):
    import devplacepy.services.bot.monitor as mod

    monkeypatch.setattr(mod, "MONITOR_DIR", tmp_path)
    monitor = BotMonitor()
    monitor.store_image(1, b"")
    assert 1 not in monitor.frames
    assert monitor.read_image(1) is None


def test_drop_evicts_row_and_file(tmp_path, monkeypatch):
    import devplacepy.services.bot.monitor as mod

    monkeypatch.setattr(mod, "MONITOR_DIR", tmp_path)
    monitor = BotMonitor()
    monitor.update_meta(0, username="x")
    monitor.store_image(0, b"data")
    monitor.drop(0)
    assert 0 not in monitor.frames
    assert monitor.read_image(0) is None


def test_snapshot_sorted_and_serializable():
    monitor = BotMonitor()
    monitor.update_meta(3, username="c")
    monitor.update_meta(1, username="a")
    snap = monitor.snapshot()
    assert [row["slot"] for row in snap] == [1, 3]
    assert "frame_url" not in snap[0]
    assert snap[0]["active"] is False


def test_frame_inactive_without_image():
    frame = BotFrame(slot=0, username="z")
    assert frame.is_active() is False
    assert frame.label() == "z"
