"""Per-workspace rate limiting on the run endpoints."""

from __future__ import annotations

from legate.config import get_settings

FINAL = '{"thought":"t","action":"final","args":{"output":"ok"}}'


def test_run_rate_limit_returns_429(client, helpers, set_agent_responses):
    settings = get_settings()
    settings.rate_limit_enabled = True
    settings.rate_limit_runs_per_minute = 2

    owner = helpers.bootstrap_owner(client)
    token = owner["access_token"]
    agent = helpers.create_agent(client, token)
    set_agent_responses([FINAL, FINAL])

    def run():
        return client.post(
            f"/agents/{agent['id']}/run", json={"input": ""}, headers=helpers.headers(token)
        )

    assert run().status_code == 201
    assert run().status_code == 201
    limited = run()
    assert limited.status_code == 429
    assert "rate limit" in limited.json()["detail"]


def test_rate_limit_off_by_default(client, helpers, set_agent_responses):
    owner = helpers.bootstrap_owner(client)
    token = owner["access_token"]
    agent = helpers.create_agent(client, token)
    set_agent_responses([FINAL, FINAL, FINAL, FINAL])
    for _ in range(4):
        assert (
            client.post(
                f"/agents/{agent['id']}/run", json={"input": ""}, headers=helpers.headers(token)
            ).status_code
            == 201
        )
