# retoor <retoor@molodetz.nl>

from __future__ import annotations

from .. import economy
from .common import GameError, _lvl, conditional_update_farm
from .farm import ensure_farm, get_farm


MASTERY_COLUMN = {m.key: f"mastery_{m.key}" for m in economy.MASTERY_UPGRADES}


def upgrade_mastery(user: dict, key: str) -> dict:
    upgrade = economy.mastery_for(key)
    if not upgrade:
        raise GameError("Unknown Mastery upgrade.")
    farm = ensure_farm(user["uid"])
    column = MASTERY_COLUMN[upgrade.key]
    level = _lvl(farm, column)
    if level >= upgrade.max_level:
        raise GameError("That Mastery upgrade is maxed out.")
    cost = economy.mastery_cost(upgrade, level)
    rows = conditional_update_farm(
        farm["uid"],
        set_clause=f"mastery_points = COALESCE(mastery_points, 0) - :cost, {column} = :new_level",
        where_clause=f"COALESCE({column}, 0) = :current_level AND COALESCE(mastery_points, 0) >= :cost",
        params={"cost": cost, "new_level": level + 1, "current_level": level},
    )
    if rows == 0:
        farm = get_farm(user["uid"])
        if _lvl(farm, column) != level:
            raise GameError("That Mastery upgrade already changed - refresh and try again.")
        raise GameError("Not enough Mastery points for that upgrade.")
    return {"key": upgrade.key, "level": level + 1, "spent": cost}
