"""The pretend scenario in widget.html: a stranger sends many requests. How many does each setup let through?

Every number is an example you can edit. The price per request is the lesson's own arithmetic: 500 input
tokens at $2 per million plus 400 output tokens at $10 per million (the example in "What is a token?").
"""
from decimal import Decimal

from keyproxy import TokenBucket

CAPACITY = 5  # tickets in each bucket
REFILL_PER_SECOND = 1.0
STRANGER_REQUESTS = 1000
STRANGER_SECONDS = 10
PRICE_PER_REQUEST = (500 * Decimal(2) + 400 * Decimal(10)) / 1_000_000  # dollars, pretend


DEMO_KEY = "EXAMPLE-demo-key-do-not-use"  # the made-up key the widget shows; it opens nothing


def stranger_outcomes(limited, addresses=1):
    """One True or False per request the stranger sends: was it accepted?

    The requests are evenly spaced over STRANGER_SECONDS and take the stranger's addresses in turn.
    limited=False is a key in the page, or a server with no limits: every request is accepted.
    """
    buckets = [TokenBucket(CAPACITY, REFILL_PER_SECOND, 0.0) for _ in range(addresses)]
    return [not limited or buckets[i % addresses].take(i * STRANGER_SECONDS / STRANGER_REQUESTS) == 0.0
            for i in range(STRANGER_REQUESTS)]


def stranger_run(limited, addresses=1):
    """How many of the stranger's requests are accepted."""
    return sum(stranger_outcomes(limited, addresses))


def bill(accepted):
    return accepted * PRICE_PER_REQUEST
