"""Pure helpers inside the ccxt adapter: market->SymbolFilter parsing, deterministic client ids, token bucket."""
from __future__ import annotations

from fxhnt.adapters.exchange.binance_ccxt import RateBudget, client_id, parse_filter


def test_parse_filter_from_ccxt_market() -> None:
    market = {"id": "BTCUSDT", "limits": {"amount": {"min": 0.001}, "cost": {"min": 5.0}},
              "precision": {"amount": 0.001, "price": 0.1}}
    f = parse_filter("BTCUSDT", market)
    assert f.step_size == 0.001 and f.tick_size == 0.1 and f.min_notional == 5.0


def test_client_id_is_deterministic_and_unique_per_leg() -> None:
    a = client_id("reb20260615", "BTCUSDT", "maker")
    assert a == client_id("reb20260615", "BTCUSDT", "maker")     # deterministic (retry-safe)
    assert a != client_id("reb20260615", "BTCUSDT", "ioc")       # distinct per leg
    assert len(a) <= 36                                          # Binance clientOrderId limit


def test_rate_budget_blocks_when_exhausted() -> None:
    b = RateBudget(max_orders=2)
    assert b.try_order() and b.try_order()
    assert b.try_order() is False                                # 3rd in the window is refused
    b.note_used_weight(2399)
    assert b.weight_ok() is True
    b.note_used_weight(2401)
    assert b.weight_ok() is False                                # over the 2400/min IP weight


def test_rate_budget_production_weight_margin() -> None:
    # Production BinanceUsdmExchange.__init__ constructs:
    #   RateBudget(max_orders=int(1200*0.9), max_weight=int(2400*0.9))
    # → effective ceiling = 2160.  Verify the 10% safety margin is enforced.
    b = RateBudget(max_orders=int(1200 * 0.9), max_weight=int(2400 * 0.9))
    b.note_used_weight(2159)
    assert b.weight_ok() is True                                 # one below ceiling: still ok
    b.note_used_weight(2161)
    assert b.weight_ok() is False                                # one above ceiling: blocked
