"""The per-IP limiter budgets are env-overridable (test/PPE stacks drive the
auth endpoints repeatedly from one IP); production leaves them unset and keeps
the secure defaults. A non-positive / unparseable value falls back."""
from __future__ import annotations

import importlib

import pytest


def _reload_with(monkeypatch, **env):
    for k, v in env.items():
        if v is None:
            monkeypatch.delenv(k, raising=False)
        else:
            monkeypatch.setenv(k, v)
    import app.ratelimit as ratelimit
    return importlib.reload(ratelimit)


@pytest.fixture(autouse=True)
def _restore():
    yield
    # Leave the module in its default state for other tests.
    import app.ratelimit as ratelimit
    importlib.reload(ratelimit)


def test_defaults_when_unset(monkeypatch):
    rl = _reload_with(monkeypatch, RATELIMIT_OTC_REQUEST_MAX=None, RATELIMIT_VERIFY_MAX=None)
    assert rl.otc_request_limiter.max_events == 5
    assert rl.verify_limiter.max_events == 10


def test_env_override(monkeypatch):
    rl = _reload_with(monkeypatch, RATELIMIT_OTC_REQUEST_MAX="1000", RATELIMIT_VERIFY_MAX="250")
    assert rl.otc_request_limiter.max_events == 1000
    assert rl.verify_limiter.max_events == 250


def test_bad_value_falls_back_to_default(monkeypatch):
    rl = _reload_with(monkeypatch, RATELIMIT_OTC_REQUEST_MAX="nope", RATELIMIT_VERIFY_MAX="0")
    assert rl.otc_request_limiter.max_events == 5   # unparseable → default
    assert rl.verify_limiter.max_events == 10       # non-positive → default
