from fxhnt.adapters.broker.bybit import BybitExecution


class _FakeCcxt:
    def __init__(self, rows):
        self._rows = rows
        self.calls = []

    def set_sandbox_mode(self, _):  # constructor calls this
        pass

    def fetch_funding_history(self, symbol=None, since=None, limit=None):
        self.calls.append({"symbol": symbol, "since": since, "limit": limit})
        return self._rows


def _exec(rows):
    ex = BybitExecution.__new__(BybitExecution)      # bypass __init__ (no network/keys)
    ex._x = _FakeCcxt(rows)                           # inject the fake ccxt client
    return ex


def test_funding_since_sums_signed_amounts():
    # ccxt funding rows: {"amount": ...} (received > 0, paid < 0)
    ex = _exec([{"amount": 1.5}, {"amount": -0.4}, {"amount": 0.9}])
    assert abs(ex.funding_since(1_700_000_000_000) - 2.0) < 1e-9
    assert ex._x.calls[0]["since"] == 1_700_000_000_000


def test_funding_since_empty_is_zero():
    assert _exec([]).funding_since(0) == 0.0


class _FakePagedCcxt:
    """Returns a FULL page (200 rows) on the first call, then a short page — proving the pagination loop
    keeps calling until it sees a short page, and advances `since` past the prior page's last timestamp."""

    def __init__(self):
        self.calls = []

    def set_sandbox_mode(self, _):
        pass

    def fetch_funding_history(self, symbol=None, since=None, limit=None):
        self.calls.append({"symbol": symbol, "since": since, "limit": limit})
        if len(self.calls) == 1:
            return [{"amount": 1.0, "timestamp": 1_700_000_000_000 + i} for i in range(200)]
        return [{"amount": 1.0, "timestamp": 1_700_000_000_300 + i} for i in range(2)]


def test_funding_since_pages_across_multiple_calls():
    ex = BybitExecution.__new__(BybitExecution)
    ex._x = _FakePagedCcxt()
    total = ex.funding_since(1_700_000_000_000)
    assert abs(total - 202.0) < 1e-9
    assert len(ex._x.calls) == 2
    assert ex._x.calls[0]["since"] == 1_700_000_000_000
    # second call's since must be past the first page's last row timestamp (1_700_000_000_199)
    assert ex._x.calls[1]["since"] == 1_700_000_000_200
    assert ex._x.calls[1]["since"] > ex._x.calls[0]["since"]
