import numpy as np

from src.gameplay import captureWatch as watchModule
from src.gameplay.captureWatch import watchCapture


def _context(paused=False, enabled=True):
    return {
        'ng_pause': paused,
        'ng_screenshot': np.zeros((50, 50), dtype=np.uint8),
        'ng_cave': {'enabled': enabled},
    }


def _advance(mocker, context, seconds):
    mocker.patch.object(watchModule, 'monotonic', return_value=seconds)
    return watchCapture(context)


def test_changing_image_never_stales(mocker):
    logSpy = mocker.patch.object(watchModule, 'logEvent')
    context = _context()

    for tick in range(40):
        context['ng_screenshot'][tick % 50, tick % 50] = tick % 255
        _advance(mocker, context, tick * 6)

    assert context['ng_pause'] is False
    logSpy.assert_not_called()


def test_frozen_image_pauses_after_two_minutes(mocker):
    logSpy = mocker.patch.object(watchModule, 'logEvent')
    context = _context()

    _advance(mocker, context, 6)  # erster Check: changedAt gesetzt
    assert context['ng_pause'] is False

    _advance(mocker, context, 127)  # 121s ohne Aenderung

    assert context['ng_pause'] is True
    assert logSpy.call_args[0][0] == 'captureStale'


def test_paused_and_disabled_are_skipped(mocker):
    logSpy = mocker.patch.object(watchModule, 'logEvent')

    context = _context(paused=True)
    _advance(mocker, context, 0)
    _advance(mocker, context, 500)
    assert 'ng_captureWatch' not in context

    context = _context(enabled=False)
    _advance(mocker, context, 0)
    _advance(mocker, context, 500)
    assert 'ng_captureWatch' not in context
    logSpy.assert_not_called()
