"""
Practice: the self-improving loop from Lab 18's script 05. The loop (an epsilon-greedy bandit)
tries four versions of the assistant on learners' messages and keeps the one with the best average
reward. You'll write the simulated learners' thumbs, their average, and the loop itself, then
watch what each reward makes the loop keep.

Fill in the TODOs, then run the tests:
    pytest test_loop_practice.py        (locally)
or press "Run tests" on the chapter page.
"""
import random
from collections import Counter

# The simulated learners (an assumption, written down so it can be argued with). For each kind of
# answer, the chance of a thumbs up and of a thumbs down; the rest of the time nobody clicks.
USERS = {
    "correct": {"up": 0.20, "down": 0.02},        # also a wrong answer they don't spot
    "wrong_spotted": {"up": 0.00, "down": 0.40},
    "refusal": {"up": 0.02, "down": 0.25},        # "I don't know", even when it's right
}


def thumb(outcome: str, refused: bool, discernment: float, rng: random.Random) -> int:
    """One learner's reaction to one answer: +1 (up), -1 (down) or 0 (no click).
    outcome is the truth's grade: "correct", "wrong" or "refused".
    - If refused: use USERS["refusal"].
    - Else if outcome is "wrong": draw rng.random(); below discernment means they spot it
      (USERS["wrong_spotted"]). Otherwise, and for every other answer, use USERS["correct"].
    - Then draw u = rng.random(): u < up gives +1, u < up + down gives -1, else 0.
    Draw from rng only in that order (the spot check only for a wrong answer), so your thumbs
    match the lab's."""
    # TODO
    raise NotImplementedError


def expected_thumb(outcome: str, refused: bool, discernment: float) -> float:
    """The average thumb (up minus down) for one answer, without drawing: what thumb() gives on
    average. A wrong answer is spotted with probability discernment."""
    # TODO
    raise NotImplementedError


def bandit(arms: list, reward, n_rounds: int, n_items: int, epsilon: float = 0.1, seed: int = 0):
    """The loop. rng = random.Random(seed). total and pulls start at 0 for every arm.
    1. Try each arm once, in order: total[a] += reward(rng.randrange(n_items), a, rng); pulls[a] += 1.
    2. For the remaining n_rounds - len(arms) rounds: if rng.random() < epsilon, pick
       rng.choice(arms); otherwise the arm with the best average total/pulls so far (on a tie, the
       first in arms; max() does that). Then reward it the same way.
    Return (kept, pulls): kept is the arm with the best average at the end."""
    # TODO
    raise NotImplementedError


def keep_counts(arms: list, reward, runs: int, n_rounds: int, n_items: int) -> Counter:
    """Run the loop once per seed 0, 1, ..., runs - 1 and count which arm each run kept."""
    # TODO
    raise NotImplementedError
