"""
计算决策时间以及最终博弈对象
A:平均决策时间是用户每轮的总操作时间/最后建立博弈关系的数量
A:最大博弈对手数量是45秒/平均决策时间
Q:那平均决策时间就是从一轮开始，到这一轮中最后一个操作完成之间的间隔对吗
A:对的
Q:具体比方说A在10秒的时候发出了请求，对面B5秒确认，那么A的决策时长是10秒还是15秒，B的决策时长是5秒还是15秒呢？
A:A是10秒，B是15秒
"""
import csv
import json
import numpy as np
from island.matches import Matches

# type
R_START = 0
A_SEND = 1
A_RECEIVE = 2
A_REPLY = 3
A_REPLY_RECEIVE = 5
A_COUNT = 4

"""
k -> "game:player:round"
v -> [(type,value)]
"""
kvstore = {}

ms = Matches.from_profile_expr(lambda r: True)
for m in ms.data:
    info = m.query('game', 'created').select('info').first()['info']
    game_end_at = int(info['game_end_at'])
    last_ts = int(info['next_start']) + 45
    round_start_ts = m.query('game', 'sunrise').orderby('created_at').raw_data
    for rno in range(1, game_end_at+1):
        for r in m.query('action', None).where(lambda x: x['rno'] == rno).orderby('created_at').raw_data:
            if r['act'] == 'request':
                key = "%s:%d:%d" % (m.name, r['from'], rno)
                if key not in kvstore:
                    kvstore[key] = [(R_START, last_ts)]
                kvstore[key].append((A_SEND, r['created_at']))
                key = "%s:%d:%d" % (m.name, r['to'], rno)
                if key not in kvstore:
                    kvstore[key] = [(R_START, last_ts)]
                kvstore[key].append((A_RECEIVE, r['created_at']))
            elif r['act'] == 'approve' or r['act'] == 'deny':
                kvstore["%s:%d:%d" % (m.name, r['from'], rno)].append((A_REPLY, r['created_at']))
                kvstore["%s:%d:%d" % (m.name, r['to'], rno)].append((A_REPLY_RECEIVE, r['created_at']))
            elif r['act'] == 'done':
                kvstore["%s:%d:%d" % (m.name, r['a'], rno)].append((A_COUNT, r['created_at']))
                kvstore["%s:%d:%d" % (m.name, r['b'], rno)].append((A_COUNT, r['created_at']))
        if rno-1 >= len(round_start_ts):
            break
        else:
            last_ts = round_start_ts[rno-1]['created_at']

result = []
total_decision_time = 0
for rk, r in kvstore.items():
    dt = 0
    cur = 0
    cnt = 0
    for k,v in r:
        if k == R_START:
            dt = v
        elif k == A_SEND:
            cur = v
        elif k == A_REPLY:
            cur = v
        elif k == A_COUNT:
            cnt += 1
    if cur == 0:
        continue
    else:
        if cnt <= 1:
            dt = cur - dt
        else:
            dt = (cur - dt) / cnt
        if dt * (cnt if cnt > 0 else 1) > 45:
            print("???%s => %f" % (rk, dt))
            continue
    total_decision_time += dt
    result.append([dt, cnt])

print("Total decision: %d, time: %d, avg: %f" % (len(result), total_decision_time, total_decision_time / len(result)))
#Total decision: 9625, time: 136406, avg: 14.172055
with open('outputs/decision.csv', 'w') as f:
    csv.writer(f).writerows(result)
