#!/usr/bin/env python3

# Usage: ./wasm_parser
# Be sure that the uploaded_log file is in the current directory

import os
import re
import subprocess
import statistics
import sys

protocol = None
protocol_map = {
    'blockage-migration': 'Blockage Migration',
    'check-blockage': 'Check Blockage',
    'issue-invite': 'Issue Invite',
    'level-up': 'Level Up',
    'migration': 'Trust Migration',
    'open-invite': 'Open Invitation',
    'redeem-invite': 'Redeem Invite',
    'trust-promo': 'Trust Promotion',
    'update-cred': 'Update Credential',
    'update-invite': 'Update Invite',
}
req_time = {}
handle_time = {}
inv = {}
time = {}
std = {}


def parse_files(log):
    for line in log:
        if matched := re.match(r'Dump buffer:\s+\".*?(\S+) client (request|handle reply) time ([\d\.]+)\s*ms', line):
            protocol = protocol_map[matched.group(1)]
            val = matched.group(3)
            if matched.group(2) == "request":
                if protocol in req_time:
                    req_time[protocol].append(float(val))
                else:
                    req_time.setdefault(protocol, []).append(float(val))
            else:
                if protocol in handle_time:
                    handle_time[protocol].append(float(val))
                else:
                    handle_time.setdefault(protocol, []).append(float(val))
    for protocol in req_time:
        inv[protocol] = list(map(lambda x, y: x + y, handle_time[protocol], req_time[protocol]))
        time[protocol] = sum(inv[protocol])/len(req_time[protocol])
        std[protocol] = statistics.stdev(inv[protocol])

with open("uploaded_log", "r") as uploaded:
        parse_files(uploaded)

# The order in which we output the protocols
protocol_list = [
    'Open Invitation',
    'Trust Promotion',
    'Trust Migration',
    'Level Up',
    'Issue Invite',
    'Redeem Invite',
    'Check Blockage',
    'Blockage Migration',
    'Update Invite',
    'Update Credential',
]

print("\n=== Table 2 ===\n")
print("protocol,client wasm ms")
for p in protocol_list:
    print(f"{p},{time[p]:.3f} ({std[p]:.3f})")


