import json
import csv
from pathlib import Path
from island.match import Match
from island.matches import Matches

userdata = {}
with open('wos-award\\s2.csv', 'r', encoding='utf-8') as c:
    for row in csv.reader(c):
        userdata[int(row[0])] = {
            'uid': row[0],
            'name': row[1],
            'email': row[2],
            'reward': 0,
            'participate': 0
        }
ms = Matches('wos-data-2022-1')
for m in ms.data:
    game_end_at = int(m.query('game', 'created').first()['info']['game_end_at'])
    for r in m.query('user', 'fitness').raw_data:

        if r['user'] in userdata:
            userdata[r['user']]['reward'] += float(r['fitness'])/game_end_at
            userdata[r['user']]['participate'] += 1
total=0
with open('user.reward.csv', 'w', encoding='utf-8') as out:
    writer = csv.writer(out, lineterminator='\n')
    writer.writerow(['uid', 'name', 'email', 'reward', 'participate'])
    for k,v in userdata.items():
        if v['reward'] == 0:
            continue
        r = round(v['reward'], 2)
        writer.writerow([k, v['name'], v['email'], r, v['participate']])
        total += r

print("total: %.2f" % (total))
