#!/usr/bin/env python2
# -*- coding: utf-8 -*-
from __future__ import print_function

import argparse

from time import time
from infra.yasm.yasmapi import GolovanRequest
from operator import attrgetter


class Service :
    def __init__(self, name):
        self.name = name
        self.counter = 0.0
        self.fail_sum = 0.0
        self.request_sum = 0.0
        self.fail_perc_sum = 0.0
        self.fail_max = 0.0
        self.fail_perc_max = 0.0

    def add(self, cur_fail, cur_requests):
        if cur_requests > 0 :
            cur_fail_perc = float(cur_fail) / float(cur_requests)
        else:
            cur_fail_perc = 0
        self.fail_sum = self.fail_sum + cur_fail
        self.request_sum = self.request_sum + cur_requests
        self.fail_perc_sum = self.fail_perc_sum + cur_fail_perc
        self.counter = self.counter + 1
        self.fail_max = max(self.fail_max, cur_fail)
        self.fail_perc_max = max(self.fail_perc_max, cur_fail_perc)

    def finalize(self):
        self.fail = self.fail_sum / self.counter
        self.fail_perc = 100.0 * self.fail_perc_sum / self.counter
        self.fail_perc_max = 100.0 * self.fail_perc_max

    def print(self) :
        print(self.name)
        # print('  counter = ', int(self.counter))
        if self.counter > 0 :
            print('  request_sum = ', self.request_sum)
            print('  fail = ', self.fail)
            print('  fail_perc = ', self.fail_perc)
            print('  fail_max = ', self.fail_max)
            print('  fail_perc_max = ', self.fail_perc_max)
        else:
            print('counter == 0')


def print_top(services, key):
    print('\n')
    print('sorted by ', key)
    services.sort(key=attrgetter(key), reverse=True)
    for i in xrange(min(5, len(services))):
        services[i].print()


def print_zero_requests(services):
    print('\n')
    print('zero requests')
    res = []
    for x in services:
        if x.request_sum == 0:
            res.append(x.name)
    print(res)


def extract_service(line):
    start = line.find('"')
    finish = line.find('"', start + 1)
    return line[start + 1 : finish]


def collect_service_names(filename):
    services = []

    previousLineReport = False

    with open(filename) as f:
        for line in f:
            if 'report = {' in line:
                previousLineReport = True
                continue
            if previousLineReport:
                previousLineReport = False
                if 'uuid' in line:
                    services.append(extract_service(line))
                else:
                    if 'refers' in line:
                        if extract_service(line) not in services:
                            print(line)
                    else:
                        print(line)
    print(services)
    return services


def print_services(service_names):
    host = "ASEARCH"
    period = 3600  # час
    et = time() - period * 5  # Интересуют последние гарантированно агрегированные точки
    st = et - period * 24

    services = []

    for service_name in service_names:
        service = Service(service_name)
        signals = [
            'itype=balancer;prj=l7-balancer-term;ctype=prod,prestable,experiment:balancer_report-report-{}-backend_fail_summ'.format(service.name),
            'itype=balancer;prj=l7-balancer-term;ctype=prod,prestable,experiment:balancer_report-report-{}-requests_summ'.format(service.name)
        ]

        for timestamp, values in GolovanRequest(host, period, st, et, signals):
            service.add(values[signals[0]], values[signals[1]])

        service.finalize()
        service.print()
        services.append(service)

    # print_top(services, 'fail_sum')
    # print_top(services, 'fail_perc_sum')
    # print_top(services, 'fail_max')

    print_zero_requests(services)

    print_top(services, 'fail_perc_max')

    print(' \n!!filtered!!')
    for s in services:
        if s.fail_perc > 0.1 and s.fail > 100:
            s.print()


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('-c', '--config')
    args = parser.parse_args()
    service_names = collect_service_names(args.config)
    print_services(service_names)


if __name__ == '__main__':
    main()
