import json
from pathlib import Path
from island.match import Match

result = {}

# = game_end_at + 1
MAX_ROUND = 29

for f in Path('wos-data-2022-pd').iterdir():
    p = Path(f)
    if p.suffix == '.json':
        name = p.stem
        m = Match.read_from_json(str(f))
        info = m.query('game', 'created').select('info').first()['info']
        conf = json.loads(info['config'])
        game_end_at = int(info['game_end_at'])
        survivals = {}
        foods = {}
        survivals[0] = []
        for p in m.query('player', 'join').select('pid').raw_data:
            foods[p['pid']] = conf['start_resource']
            survivals[0].append(p['pid'])

        for i in range(1, game_end_at + 1):
            survivals[i] = []
            for a in m.query('action', 'done').where(lambda x: x['rno'] == i).raw_data:
                foods[a['a']] += conf['payoffs']["%s%s" % (a['act_a'], a['act_b'])][0] * a['tr'] / 1440.0
                foods[a['b']] += conf['payoffs']["%s%s" % (a['act_a'], a['act_b'])][1] * a['tr'] / 1440.0
            for j in foods.keys():
                foods[j] -= conf['rounds']['consumption']
                if foods[j] > 0:
                    survivals[i].append(j)

        result[name] = survivals

# print(json.dumps(result))

with open("outputs/survivals_new.json", 'w') as f:
    json.dump(result, f)

average = [0] * MAX_ROUND
for k, v in result.items():
    for r, l in v.items():
        average[int(r)] += len(l)

for i in range(MAX_ROUND):
    average[i] /= len(result)

idx = []
s = []
for i in range(1, MAX_ROUND):
    idx.append(str(i))
    s.append("%.1f" % average[i])

print(" & ".join(idx))
print(" & ".join(s))
