"""Vending machine as an explicit state machine: idle -> has_money -> dispensing -> idle.

(See patterns/behavioral.py for the class-per-state version of the State pattern.)
"""
from __future__ import annotations

from dataclasses import dataclass
from typing import Dict, List, Tuple

COINS = (25, 10, 5)  # cents; change is returned greedily (works for these canonical denominations)


@dataclass
class Product:
    name: str
    price: int  # cents
    quantity: int


class VendingMachine:
    def __init__(self, products: Dict[str, Product]):
        self.products = products
        self.balance = 0
        self.state = "idle"

    def insert(self, cents: int) -> None:
        if cents not in COINS and cents not in (100,):
            raise ValueError("coin or note not accepted")
        self.balance += cents
        self.state = "has_money"

    def select(self, code: str) -> Tuple[str, List[int]]:
        if self.state != "has_money":
            raise RuntimeError("insert money first")
        product = self.products.get(code)
        if product is None:
            raise KeyError("unknown product")
        if product.quantity == 0:
            raise RuntimeError("sold out")
        if self.balance < product.price:
            raise RuntimeError(f"insert {product.price - self.balance} more cents")
        self.state = "dispensing"
        product.quantity -= 1
        change = self._make_change(self.balance - product.price)
        self.balance = 0
        self.state = "idle"
        return product.name, change

    def cancel(self) -> List[int]:
        refund = self._make_change(self.balance)
        self.balance = 0
        self.state = "idle"
        return refund

    @staticmethod
    def _make_change(amount: int) -> List[int]:
        out = []
        for coin in COINS:
            while amount >= coin:
                out.append(coin)
                amount -= coin
        if amount:
            raise RuntimeError("cannot make exact change")
        return out
