import json
import glob

winner = {}
pid2uid = {}
score = {}

act_set = {'accept_failed', 'request', 'deny'}

username = {}
with open("..\\username.csv", encoding='utf-8') as f:
    for l in f:
        parts = l.strip().split(',')
        username[int(parts[0])] = parts[1]

G_NAME = {}
filelist = glob.glob("*.json", recursive=False)
filelist.sort()

for idx, fn in enumerate(filelist):
    G_NAME[fn.split(".")[0]] = idx + 1
    with open(fn, encoding='utf-8') as f:
        data = json.load(f)
    total_round = int(data[0]['info']['game_end_at'])
    uids = {}
    for r in data[::-1]:
        if r['cat'] == 'game' and r['act'] == 'winner':
            for uid in r['data']:
                uids[uid] = dict(h=[[] for _ in range(total_round)])
            break

    for uid, d in uids.items():
        if uid not in winner:
            winner[uid] = {}

    no_tr = False
    for r in data:
        if r['cat'] == 'game' and r['act'] == 'created':
            config = json.loads(r['info']['config'])
            no_tr = 'no_tr' in config and config['no_tr']
        if r['cat'] == 'player' and r['act'] == 'join':
            if r['uid'] in uids:
                pid2uid[r['pid']] = r['uid']
                winner[r['uid']][fn] = uids[r['uid']] | {'p': r['pid'], 'no_tr': no_tr}
        if r['cat'] == 'action':
            if r['act'] == 'done':
                if r['a'] in pid2uid:
                    winner[pid2uid[r['a']]][fn]['h'][r['rno'] - 1].append(r)
                elif r['b'] in pid2uid:
                    winner[pid2uid[r['b']]][fn]['h'][r['rno'] - 1].append(r)
            elif r['act'] in act_set:
                if r['from'] in pid2uid:
                    winner[pid2uid[r['from']]][fn]['h'][r['rno'] - 1].append(r)

symbol = dict(D='🔪', C='🤝')
ACT_DONE_NO_TR = "%d. TA出了%s，对方%d出了%s"
ACT_DONE = ACT_DONE_NO_TR + "，消耗时间资源%d。"

with open("result.txt", "w", encoding="utf-8") as f:
    for uid in winner.keys():
        print("\n\n玩家：", username[uid], file=f)
        for g, data in winner[uid].items():
            print("在第%d场比赛中获胜" % G_NAME[g.split('.')[0]], file=f)
            if data['no_tr']:
                for i, h in enumerate(data['h']):
                    print("第%d轮：" % (i + 1), file=f)
                    for j, r in enumerate(h):
                        if r['act'] == 'done':
                            if r['a'] == data['p']:
                                print(ACT_DONE_NO_TR % (j + 1, symbol[r['act_a']], r['b'], symbol[r['act_b']]), file=f)
                            else:
                                print(ACT_DONE_NO_TR % (j + 1, symbol[r['act_b']], r['a'], symbol[r['act_a']]), file=f)
                        elif r['act'] == 'accept_failed':
                            print("%d. TA与%d之间的博弈未能完成。" % (j + 1, r['to']), file=f)
                        elif r['act'] == 'request':
                            print("%d. TA向%d发出了%s请求。" % (j + 1, r['to'], symbol[r['action']]), file=f)
                        elif r['act'] == 'deny':
                            print("%d. TA拒绝了%d的博弈请求。" % (j + 1, r['to']), file=f)
            else:
                for i, h in enumerate(data['h']):
                    print("第%d轮：" % (i + 1), file=f)
                    for j, r in enumerate(h):
                        if r['act'] == 'done':
                            if r['a'] == data['p']:
                                print(ACT_DONE % (j + 1, symbol[r['act_a']], r['b'], symbol[r['act_b']], r['tr']),
                                      file=f)
                            else:
                                print(ACT_DONE % (j + 1, symbol[r['act_b']], r['a'], symbol[r['act_a']], r['tr']),
                                      file=f)
                        elif r['act'] == 'accept_failed':
                            print("%d. TA因为时间资源不足不得不拒绝了%d。" % (j + 1, r['to']), file=f)
                        elif r['act'] == 'request':
                            print("%d. TA向%d发出了%s请求，时间资源%d。" % (j + 1, r['to'], symbol[r['action']], r['tr']),
                                  file=f)
                        elif r['act'] == 'deny':
                            print("%d. TA拒绝了%d的博弈请求。" % (j + 1, r['to']), file=f)
