from island.match import Match
from island.matches import Matches
import json

matches = Matches('wos-data-2022-1')
crs = []
for m in matches.data:
    game_end_at = int(m.query('game', 'created').first()['info']['game_end_at'])
    games = [{} for _ in range(game_end_at)]
    for round in range(1, game_end_at+1):
        rows = m.query('action', 'done').where(lambda x: x['rno'] == round).raw_data
        for row in rows:
            players = [f"{row['a']}-{row['b']}", f"{row['b']}-{row['a']}"]
            log_id = -1
            for p in players:
                if p in games[round-1]:
                    log_id = games[round-1][p]
            if log_id != -1:
                print("Collision detected: match=%s, row=%s, collision_log_id=%d" %(m.name, json.dumps(row), log_id))
                print("History of this two players:")
                logs = m.query('action', 'done').where(lambda x: f"{x['a']}-{x['b']}" in players).raw_data + \
                       m.query('action', 'request').where(lambda x: f"{x['from']}-{x['to']}" in players).raw_data + \
                       m.query('action', 'approve').where(lambda x: f"{x['from']}-{x['to']}" in players).raw_data
                for log in sorted(logs, key=lambda a: a['log_id']):
                    print(json.dumps(log))

            else:
                for p in players:
                    games[round-1][p] = row['log_id']
