"""Print every number the lesson computes. Run it from this folder: python3 show_numbers.py"""
from decimal import Decimal

from keyproxy import TokenBucket
from scenario import (CAPACITY, PRICE_PER_REQUEST, REFILL_PER_SECOND, STRANGER_REQUESTS, STRANGER_SECONDS,
                      bill, stranger_run)

print(f"== Pretend price of one chat request: ${PRICE_PER_REQUEST} (500 input tokens at $2/M + 400 output tokens at $10/M)")

print("\n== A bucket of 3 tickets that gains 1 ticket per second, requests at the times shown")
bucket = TokenBucket(3, 1.0, 0.0)
print("  time (s) | tickets before | outcome")
for t in (0.0, 0.1, 0.2, 0.3, 0.8, 1.3, 1.4):
    wait = bucket.take(t)
    before = bucket.level + (0 if wait else 1)
    outcome = "accepted" if not wait else f"refused, try again in {wait:.1f} s"
    print(f"  {t:8.1f} | {before:14.1f} | {outcome}")

print(f"\n== The stranger: {STRANGER_REQUESTS:,} requests in {STRANGER_SECONDS} s "
      f"({STRANGER_REQUESTS // STRANGER_SECONDS}/s), bucket of {CAPACITY} gaining {REFILL_PER_SECOND:g}/s per address")
rows = [("Key in the page", False, 1), ("Server, no limits", False, 1), ("Server, rate limit, 1 address", True, 1)]
rows += [(f"Server, rate limit, {n} addresses", True, n) for n in (20, 100)]
print("  setup | accepted | pretend bill")
for name, limited, addresses in rows:
    accepted = stranger_run(limited, addresses)
    print(f"  {name} | {accepted:,} | ${bill(accepted):.3f}")

last = (STRANGER_REQUESTS - 1) * STRANGER_SECONDS / STRANGER_REQUESTS
print("\n== Why one address gets 14, not 15")
print(f"  {CAPACITY} tickets at the start + {last:g} s x {REFILL_PER_SECOND:g}/s before the last request "
      f"= {CAPACITY + last * REFILL_PER_SECOND:g} tickets, and only whole requests count")
