#!/usr/bin/env python
# -*- coding: utf-8 -*-

import sys
import json
import logging
import dateutil.parser
import datetime
import time
import requests
import direct_juggler.juggler as dj

sys.path.insert(0, '/opt/downtime-db-utils')
import downtime_db_utils as utils

requests.packages.urllib3.disable_warnings()

SERVICE_NAME = "dc-downtimes-parser.working"
ALLDB_CONFIG = "/etc/yandex-direct/alldb-config.json"
with open("/etc/direct-tokens/oauth_infra_robot-direct-infra", "r") as fh:
    ROBOT_TOKEN = fh.read().strip()

# Yandex duty sheet (service and infrastructure schedule)
INFRA_SERVICE_ID = "154"
SEVERITY = "major"


def make_request(url):
    for i in range(5):
        try:
            req = requests.get(url)
            if req.status_code != 200:
                logging.error('request "%s" failed, status code: %d' % (url, req.status_code))
                continue
            return req

        except:
            logging.exception('request "%s" failed' % url)
            time.sleep(1)

    return None


def get_dc2hosts():
    dc2hosts = {}

    try:
        direct_hosts = make_request('https://c.yandex-team.ru/api/groups2hosts/direct').content.splitlines()
        batch_size = 50
        for i in xrange(0, len(direct_hosts), batch_size):
            data = requests.get('https://c.yandex-team.ru/api/hosts/%s?format=json' % ",".join(
                direct_hosts[i: i + batch_size]
            )).json()
            for item in data:
                if item['root_datacenter'] not in dc2hosts:
                    dc2hosts[item['root_datacenter']] = []

                dc2hosts[item['root_datacenter']].append(item['fqdn'])

        return dc2hosts
    except:
        logging.exception("can't get data from conductor")

    # если кондуктор не доступен, получаем хосты из alldb-конфига
    with open(ALLDB_CONFIG, "r") as fh:
        config = json.load(fh)['instances']

    dc2hosts = {}
    for instance in config:
        for host in config[instance]["replicas"]:
            if not host['dc'] in dc2hosts:
                dc2hosts[host['dc']] = []

            dc2hosts[host['dc']].append(host['host'])

    for dc in dc2hosts:
        dc2hosts[dc] = list(set(dc2hosts[dc]))

    return dc2hosts


def main():
    utils.zkh.start()
    utils.get_lock()

    dc2hosts = get_dc2hosts()
    events = requests.get(
        'https://infra-api.yandex-team.ru/v1/events?from=%d&serviceId=%s&severity=%s' % (
            time.time(), INFRA_SERVICE_ID, SEVERITY
        ),
        headers={'Authorization': 'Oauth %s' % ROBOT_TOKEN},
        verify=False
    ).json()

    for event in events:
        downtime_hosts = [host for dc in dc2hosts if event.get(dc, '') for host in dc2hosts[dc]]
        if downtime_hosts:
            logging.info("found event with id %s and title '%s' with hosts under downtime: %s" % (
                str(event['id']), event['title'], ", ".join(downtime_hosts))
            )
            utils.send_data_to_zk(
                downtime_hosts,
                datetime.datetime.fromtimestamp(event['start_time']),
                "infra (id: %d, title: %s)" % (event['id'], event['title'])
            )

    utils.zkh.stop()


if __name__ == '__main__':
    logging.basicConfig(
        format=u'%(levelname)-8s [%(asctime)s] %(message)s',
        level=logging.INFO,
    )

    try:
        logging.info("START")
        main()
        dj.queue_events([{'service': SERVICE_NAME, 'status': 'OK', 'description': ''}])
        logging.info("END")

    except Exception as e:
        logging.exception("unexpected exception")
        dj.queue_events([{
            'service': SERVICE_NAME,
            'status': 'CRIT',
            'description': "unexpected exception (%s) %s" % (type(e), e)
        }])

