#!/usr/bin/env python
from __future__ import print_function, unicode_literals

import argparse
import os
import sys

from object_validator import String
from sepelib.core import config

from walle.clients import bot
from walle.main import load_config
from walle.util.validation import ApiDictScheme, StringToInteger


def mk_request(hostname, comment):
    params = {
        'comment': comment,
        'initiator': os.environ['USER'],
        'name': hostname,
        'operation': 'body',
        'problem': 154,
        'eine_code': '2nd_time_node',
        'email': 'yes'
    }

    response = bot.json_request(
        path="/api/v3/dc/request",
        params=params,
        authenticate=True,
        scheme=ApiDictScheme({
            "result": ApiDictScheme({
                "Id": StringToInteger(),
                "Status": String(),
                "StNum": String()
            }),
        })
    )

    result = response["result"]
    if result["Status"] not in ("NEW", "WORK"):
        print("Failed to create an admin request in Bot: %s.", response, file=sys.stderr)
        exit(10)
    else:
        print("created bot request id {bot_id} ticket https://st.yandex-team.ru/{ticket}".format(
            bot_id=result['Id'], ticket=result['StNum']))


def _parse_args():
    parser = argparse.ArgumentParser(description="Temporary script to create 2nd_time_node requests.")
    parser.add_argument("-c", "--config", help="configuration file path")
    parser.add_argument("-d", "--debug", action="store_true", help="Set logging level to 'debug'")

    parser.add_argument("hostname", help="Hostname")
    parser.add_argument("comment", help="Request description")

    config.augment_args_parser(parser)
    return parser.parse_args()


def main():
    args = _parse_args()
    load_config(args)

    mk_request(args.hostname, args.comment)


if __name__ == "__main__":
    main()
