# wcs/games/demo/moderator.py
"""The demo moderator: welcome, round intros, results and transitions from resources/demo/millionaire/moderator.json.

The same lines serve every title (placeholders {title} {subject} {game} {money} {next_money} {round} {next_round});
which variant of a line is used depends only on the title and the round, so a game always reads the same.
"""
import zlib
from functools import lru_cache

from wcs.games.demo import catalog
from wcs.games.millionaire_prompts import MONEY_AMOUNTS

FINAL_ROUND = catalog.ROUNDS


@lru_cache(maxsize=1)
def _texts():
    return catalog.read_json('moderator.json')


def tier(round_num):
    """Difficulty tier of a round: easy 1-3, medium 4-6, hard 7-8, final 9."""
    return 'easy' if round_num <= 3 else 'medium' if round_num <= 6 else 'hard' if round_num < FINAL_ROUND else 'final'


def _pick(variants, title, *salt):
    return variants[zlib.crc32('|'.join((title.id,) + tuple(str(s) for s in salt)).encode('utf-8')) % len(variants)]


def _fill(text, title, **values):
    texts = _texts()
    subject = texts['subject'][title.media].format(title=title.title)
    return text.format(title=title.title, subject=subject, game=texts['game_name'][title.media], **values)


def welcome(title):
    return _fill(_pick(_texts()['welcome'], title, 'welcome'), title)


def rules(title):
    return _fill(_pick(_texts()['rules'], title, 'rules'), title)


def intro(title, round_num):
    return _fill(_pick(_texts()['intro'][str(round_num)], title, 'intro', round_num), title,
                 money=MONEY_AMOUNTS[round_num], round=round_num)


def result(title, round_num, is_correct):
    group = _texts()['correct' if is_correct else 'wrong'][tier(round_num)]
    return _fill(_pick(group, title, 'result', round_num, is_correct), title)


def transition(title, round_num, is_correct):
    """What follows a result: the next round when right, the farewell when wrong or after the last round."""
    if is_correct and round_num < FINAL_ROUND:
        return _fill(_pick(_texts()['transition'][str(round_num + 1)], title, 'transition', round_num), title,
                     next_round=round_num + 1, next_money=MONEY_AMOUNTS[round_num + 1])
    return _fill(_pick(_texts()['farewell']['win' if is_correct else 'lose'], title, 'farewell', round_num), title)
