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

import httplib
import json
import string
import logging
import sys
import os
import re

token = os.getenv("OAUTH_ST")

if token is None:
    print("OAUTH_ST environment value must be set")
    sys.exit(1)

oauth_header = {
    "Authorization" : "OAuth %s" % token,
    "Content-Type" : "application/json"
}

def request_st_api(url, method = "GET", body = "") :
    connection = httplib.HTTPSConnection("st-api.yandex-team.ru")
    connection.request(method, url, body, oauth_header)
    response = connection.getresponse()
    return json.loads(response.read())

def get_required_fields(queue):
    content = request_st_api("/v2/queues/%s/fields" % queue)

def get_tickets(queue):
    return request_st_api("/v2/issues?filter=queue:%s&filter=resolution:empty()&perPage=100&page=1" % queue)

def get_ticket_content(ticket_key):
    return request_st_api("/v2/issues/%s?pretty=true&expand=links" % ticket_key)

def get_ticket_duplicates_count(ticket_obj):
    if "duplicatesCount" in ticket_obj:
        return ticket_obj["duplicatesCount"]
    else:
        return 0

def get_ticket_otrs_links_count(ticket_obj):
    if "remotelinks" not in ticket_obj:
        return 0

    otrs_links = 0
    for link in ticket_obj["remotelinks"]:
        if "display" in link and "ru.yandex.otrs" in link["display"]:
            otrs_links += 1

    return otrs_links

def update_ticket_duplicates_count(ticket_key, new_duplicates_count):
    return request_st_api("/v2/issues/%s" % ticket_key, "PATCH", json.dumps({ "duplicatesCount": new_duplicates_count }))

if __name__ == "__main__":
    log_basename = os.path.basename(os.path.splitext(__file__)[0]) + '.log'
    log_filename = os.path.join(os.getenv("LOG_DIR", ""), log_basename)
    logging.basicConfig(level=logging.INFO, format='[%(asctime)s] %(levelname)s %(thread)d %(message)s', filename=log_filename)

    for queue in ["HOME", "TURBOSUP", "WMCSUPPORT", "WMCFEATURE", "SITESEARCH", "XML", "XMLSUPPORT", "ZORAHELPDESK"]:
        try:
            for ticket in get_tickets(queue):
                try:
                    ticket_key = ticket["key"]
                    ticket_obj = get_ticket_content(ticket_key)

                    duplicates_count = get_ticket_duplicates_count(ticket_obj)
                    otrs_links = get_ticket_otrs_links_count(ticket_obj)
                    if duplicates_count != otrs_links:
                        update_ticket_duplicates_count(ticket_key, otrs_links)
                        logging.info("%s, %s, duplicatesCount %d -> %d", queue, ticket_key, duplicates_count, otrs_links)
                except Exception as e:
                    logging.error(e)
        except Exception as e:
            logging.error(e)
