import os
import json
import requests
from functools import partial


OAUTH_TOKEN = os.getenv('OAUTH_TOKEN')


"""
    Gererates json for https://yasm.yandex-team.ru/panel/staff_net
"""


def make_net_signal(name, itype=None, balancer=None, project=None, instance=None, color=None):
    tags = []
    if itype:
        tags.append(f'itype={itype}')
    if itype == 'qloudrouter' and balancer:
        tags.append(f'ctype={balancer}')
    if itype == 'qloud' and project:
        tags.append(f'prj={project}')
    if instance:
        tags.append(f'tier={instance}')

    signal = {
        'tag': ';'.join(tags),
        'host': 'QLOUD',
        'name': name,
    }

    if color:
        signal.update({'color': color})

    return signal



def get_environment_info(project, application, environment):
    host = 'https://qloud-ext.yandex-team.ru/api/v1/environment/stable'
    env = f'{project}.{application}.{environment}'

    if not hasattr(get_environment_info, '_cache'):
        get_environment_info._cache = {}
    elif env in get_environment_info._cache:
        return get_environment_info._cache[env]

    response = requests.get(
        f'{host}/{env}',
        headers={'Authorization': f'OAuth {OAUTH_TOKEN}'}
    ).json()

    get_environment_info._cache[env] = response
    return response



def make_chart(row, col, project='tools', application='staff', environment='staff-back', component=None):
    env = get_environment_info(project, application, environment)
    signals = []

    make_signal = partial(
        make_net_signal,
        itype=env['itype'],
        balancer=env['name'],
        project=env['objectId'],
    )

    if not component:
        signals.append(make_signal(name='portoinst-net_tx_mb_summ'))
        signals.append(make_signal(name='portoinst-net_rx_mb_summ'))
        signals.append(make_signal(name='sum(portoinst-net_tx_mb_summ, portoinst-net_rx_mb_summ)'))
        signals.append(make_signal(name='portoinst-net_guarantee_mb_summ', color='#169833'))
    else:
        instances = [instance['instanceId'] for instance in env['components'][component]['runningInstances']]
        for instance in instances:
            signals.append(make_signal(name='sum(portoinst-net_tx_mb_summ, portoinst-net_rx_mb_summ)', instance=instance))
        signals.append(make_signal(name='portoinst-net_guarantee_mb_summ', instance=instances[0], color='#169833'))


    return {
        'type': 'graphic',
        'width': 1,
        'height': 1,
        'row': row,
        'col': col,
        'title': '.'.join(filter(None, [application, environment, component])),
        'stacked': False,
        'normalize': True,
        'disableDomainErrors': True,
        'signals': signals,
    }


if __name__ == '__main__':
    charts = []

    charts.append(make_chart(2, 1, application='staff', environment='staff'))
    charts.append(make_chart(2, 2, application='staff', environment='staff', component='balancer-l7'))
    charts.append(make_chart(3, 1, application='staff', environment='nginx-production'))
    charts.append(make_chart(3, 2, application='staff', environment='nginx-production', component='nginx'))
    charts.append(make_chart(4, 1, application='staff', environment='witchery-production'))
    charts.append(make_chart(4, 2, application='staff', environment='witchery-production', component='back'))
    charts.append(make_chart(5, 1, application='staff-www', environment='production'))
    charts.append(make_chart(5, 2, application='staff-www', environment='production', component='frontend'))
    charts.append(make_chart(6, 1, application='staff-mobile', environment='prod'))
    charts.append(make_chart(6, 2, application='staff-mobile', environment='prod', component='frontend'))

    charts.append(make_chart(2, 3, application='staff', environment='staff-back'))
    charts.append(make_chart(2, 4, application='staff', environment='staff-back', component='balancer-l7'))
    charts.append(make_chart(3, 3, application='staff', environment='production'))
    charts.append(make_chart(3, 4, application='staff', environment='production', component='back'))
    charts.append(make_chart(4, 3, application='staff', environment='production', component='back-api'))
    charts.append(make_chart(4, 4, application='staff', environment='production', component='callcenter'))
    charts.append(make_chart(5, 3, application='staff', environment='auth-checker-production'))
    charts.append(make_chart(5, 4, application='staff', environment='auth-checker-production', component='back'))

    print(json.dumps({
        'user': 'cracker',
        'title': 'Сеть в стаффе',
        'type': 'panel',
        'editors': [],
        'charts': charts + [
            {
                "type": "text",
                "width": 2,
                "height": 1,
                "row": 1,
                "col": 1,
                "text": "staff balancer"
            },
            {
                "type": "text",
                "width": 2,
                "height": 1,
                "row": 1,
                "col": 3,
                "text": "staff-back balancer"
            }
        ],
    }))
