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

user_data = {} # user_id => {m => match_count, s => total_score, w => total_win}
winners = {} # match_id => [user_id]

ms = Matches('wos-data-2022-12-16')
for m in ms.data:
    print(m.name)
    if 'G' in m.name:
        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'] not in user_data:
                user_data[r['user']] = dict(m=0,s=0,w=0)
            user_data[r['user']]['m'] += 1
            user_data[r['user']]['s'] += float(r['fitness'])/game_end_at
        r = m.query('game', 'winner').first()
        for u in r['data']:
            user_data[u]['w'] += 1
        winners[m.name] = r['data']

    else:
        player_data = {} #player_id => game_count
        user_data_this_match = {} # user_id => {g => game_count, s => avg_score}
        for r in m.query('action', 'done').raw_data:
            for p in [r['a'], r['b']]:
                if p not in player_data:
                    player_data[p] = 1
                else:
                    player_data[p] += 1

        for r in m.query('player', 'join').raw_data:
            if r['pid'] in player_data:
                user_data_this_match[r['uid']] = dict(g=player_data[r['pid']], s=0)

        for r in m.query('user', 'fitness').raw_data:
            if r['user'] in user_data_this_match:
                user_data_this_match[r['user']]['s'] = float(r['fitness'])/user_data_this_match[r['user']]['g']
                if r['user'] not in user_data:
                    user_data[r['user']] = dict(m=1, s=user_data_this_match[r['user']]['s'], w=0)
                else:
                    user_data[r['user']]['m'] += 1
                    user_data[r['user']]['s'] += user_data_this_match[r['user']]['s']

        top1 = dict(s=0, u=[])
        top2 = dict(s=0, u=[])
        top3 = dict(s=0, u=[])
        for k,v in user_data_this_match.items():
            if v['s'] > top1['s']:
                top3 = top2
                top2 = top1
                top1 = dict(s=v['s'], u=[k])
            elif v['s'] == top1['s']:
                top1['u'].append(k)
            elif v['s'] > top2['s']:
                top3 = top2
                top2 = dict(s=v['s'], u=[k])
            elif v['s'] == top2['s']:
                top2['u'].append(k)
            elif v['s'] > top3['s']:
                top3 = dict(s=v['s'], u=[k])
            elif v['s'] == top3['s']:
                top3['u'].append(k)

        print('Match: ', m.name)
        print('top1: ', json.dumps(top1))
        print('top2: ', json.dumps(top2))
        print('top3: ', json.dumps(top3))
        winners[m.name] = top1['u']+top2['u']+top3['u']
        for t in [top1, top2, top3]:
            for u in t['u']:
                user_data[u]['w'] += 1


with open('user.avg.score.csv', 'w', encoding='utf-8') as f:
    writer = csv.writer(f, lineterminator='\n')
    for k,v in user_data.items():
        avg_score = v['s']/v['m']
        writer.writerow([k, v['s'], v['w'], avg_score])

with open('winners.json', 'w', encoding='utf-8') as f:
    json.dump(winners, f)
