"""Enumerate bookings for the three workshops. All money is in counters."""
import json
from itertools import combinations, permutations, product
from pathlib import Path

NAMES = ("Tiles", "Jugs", "Bowls")
DEMAND = dict(zip(NAMES, (4, 3, 2)))
BENEFIT = dict(zip(NAMES, (9, 8, 8)))
PRICE = 6
EARLY = ("Mon", "Tue", "Wed")
LATE = ("Thu", "Fri am", "Fri pm")


def trigger(order):
    total = 0
    for shop in order:
        total += DEMAND[shop]
        if total > 5:
            return shop
    return None


def charges(order, rule):
    if rule == "crossing":
        return {shop: PRICE * (shop == trigger(order)) for shop in NAMES}
    orders = list(permutations(order))
    return {shop: sum(PRICE for candidate in orders if trigger(candidate) == shop)
            / len(orders) for shop in NAMES}


def account(profile, delay_cost, rule, benefits):
    arrivals = sorted((profile[i] == "L", i, shop)
                      for i, shop in enumerate(NAMES) if profile[i] != "X")
    order = tuple(row[2] for row in arrivals)
    bills = charges(order, rule)
    payoff = tuple(0 if date == "X" else benefits[shop] - bills[shop]
                   - delay_cost[i] * (date == "L")
                   for i, (shop, date) in enumerate(zip(NAMES, profile)))
    assert sum(bills.values()) == PRICE * (trigger(order) is not None)
    return payoff


def equilibria(moves, delay, rule, benefits):
    schedules = list(product(moves, repeat=3))
    payoffs = {s: account(s, delay, rule, benefits) for s in schedules}
    return ["".join(s) for s in schedules if all(
        payoffs[s][i] >= payoffs[s[:i] + (choice,) + s[i+1:]][i]
        for i in range(3) for choice in moves)]


def run():
    orders = [{"order": order, "payer": trigger(order)} for order in permutations(NAMES)]
    mean_shares = charges(NAMES, "average")
    assert list(mean_shares.values()) == [4, 1, 1]
    for n in range(4):
        for group in combinations(NAMES, n):
            for order in permutations(group):
                for rule in ("crossing", "average"):
                    assert sum(charges(order, rule).values()) == 6 * (trigger(order) is not None)
    scenarios = [
        ("Only Jugs can wait cheaply", "ELX", (7, 1, 7), BENEFIT, (["ELE"], ["EEE"])),
        ("All can wait cheaply", "ELX", (1, 1, 1), BENEFIT, ([], ["EEE"])),
        ("Opening dates bind", "EX", (7, 1, 7), BENEFIT, (["EEE"], ["EEE"])),
        ("Small order for Jugs, dates bind", "EX", (7, 1, 7), {**BENEFIT, "Jugs": 2}, (["EXE"], ["EEE"])),
    ]
    runs = []
    for name, moves, delay, benefits, expected in scenarios:
        result = {}
        for rule in ("crossing", "average"):
            stable = equilibria(moves, delay, rule, benefits)
            jug_options = {m: account(("E", m, "E"), delay, rule, benefits)[1] for m in moves}
            result[rule] = {"equilibria": stable, "jug_payoff_with_neighbours_early": jug_options}
        assert (result["crossing"]["equilibria"], result["average"]["equilibria"]) == expected
        runs.append({"name": name, "candidates_per_contract": len(moves)**3, "delay_costs": delay,
                     "gross_benefits": benefits, "results": result})
    return {"slot_demands": DEMAND, "free_slots": 5, "kiln_cost": PRICE, "orders": orders,
            "average_shares": mean_shares, "code_order": NAMES,
            "action_codes": {"E": "early", "L": "late", "X": "withdraw"}, "runs": runs}


if __name__ == "__main__":
    result = json.dumps(run(), indent=2, ensure_ascii=False) + "\n"
    print(result, end="")
    saved = Path(__file__).with_name("results.json")
    if saved.exists():
        assert json.loads(saved.read_text(encoding="utf-8")) == json.loads(result)
