"""Calculate donations"""

import re
import math


def sum_donations():
    """Count total donations"""
    resources = {
        'bbl': {},
        'kg': {},
        'pcs': {},
        'G': {},
        'g': {},
        '$': {},
    }
    with open('donations.txt', 'r') as file:
        for line in file:
            try:
                donation = re.search(r'\d.*?(bbl|kg|pcs|G|g|\$)', line).group(0)
                player = re.search(r'.*?\s\t', line).group(0).strip()
                amount, resource = donation.split(' ')
                amount = int(amount.replace('.', ''))

                if player not in resources[resource]:
                    resources[resource][player] = 0
                resources[resource][player] += amount

                if 'total' not in resources[resource]:
                    resources[resource]['total'] = 0
                resources[resource]['total'] += amount

            except Exception as exception:
                print('exception')
                print('%s %s' % (line, exception))

    return resources


def print_resources(resources):
    """Print donations per resource"""
    for resource, players in resources.items():
        print(resource)
        count = 1
        for player in sorted(players, key=players.get, reverse=True):
            print('%20s %s' % (bucks(players[player]), player))
            if count >= 10:
                break
            count += 1


def calc_reward(resources):
    """Calculate reward"""
    reward = {
        'bbl': 130,
        'kg': 120,
        'pcs': 850000,
        'g': 1250,
    }
    resource_koef = {
        'bbl': 1000000000,
        'kg': 1105000000,
        'pcs': 104000000,
        'g': 160000,
    }
    player_reward = {}
    for resource, players in resources.items():
        if resource not in reward:
            continue
        for player, amount in players.items():
            if player == 'total':
                continue
            if player not in player_reward:
                player_reward[player] = 0
            tmp_reward = reward[resource] * amount
            koef = math.floor(amount / resource_koef[resource])
            player_reward[player] += tmp_reward + round(tmp_reward / 100 * koef * 2)

    return player_reward


def print_reward(players):
    """print player rewards"""
    total = 0
    for player, reward in sorted(players.items(), key=lambda x: x[1], reverse=True):
        total += reward
        print('%20s %s' % (bucks(reward), player))

    print('total: %s' % bucks(total))


def bucks(integer):
    """Format number"""
    return '{:,}'.format(integer).replace(',', '.')


if __name__ == '__main__':
    RESOURCES = sum_donations()
    PLAYERS = calc_reward(RESOURCES)
    print_reward(PLAYERS)
    print_resources(RESOURCES)