#!/usr/bin/env python3
# Nanny API documentation here - https://docs.yandex-team.ru/nanny/reference/api/rest
import sys
import os
import logging
import requests
import urllib3

logging.basicConfig(stream=sys.stdout, format="[%(asctime)s %(levelname)s] %(message)s", level=logging.INFO)
log = logging.getLogger()
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)


def get_ya_token_path():
    return os.environ.get('NANNY_TOKEN_PATH', os.path.join(os.path.expanduser("~"), '.nanny_token'))


def get_ya_token():
    def get_token_from_file():
        try:
            with open(get_ya_token_path(), 'r') as f:
                return f.read().strip()
        except Exception:
            pass

    return os.getenv('NANNY_TOKEN') or get_token_from_file()

# To get token use - http://nanny.yandex-team.ru/ui/#/oauth/ and dump to ~/.nanny_token
token = get_ya_token()


def get_service_attrs(service_id, attrs_name):
    headers = {"Authorization": "OAuth {}".format(token), "Accept": "application/json"}
    url = "https://nanny.yandex-team.ru/v2/services/{}/{}/".format(service_id, attrs_name)

    r = requests.get(url, headers=headers, verify=False)
    r.raise_for_status()
    return r.json()


def put_service_attrs(id, attrs_name, attrs_json, comment=None):
    body = {
        "comment": comment or "-",
        "snapshot_id": attrs_json["_id"],
        "content": attrs_json["content"]
    }

    headers = {"Authorization": "OAuth {}".format(token), "Content-Type": "application/json"}
    url = "https://nanny.yandex-team.ru/v2/services/{}/{}/".format(id, attrs_name)
    r = requests.put(url, headers=headers, json=body, verify=False)
    r.raise_for_status()
    return r.json()


def post_set_snapshot_state_event(id, snapshot_id, state):
    body = {
        "type": "SET_SNAPSHOT_STATE",
        "content": {
            "snapshot_id": snapshot_id,
            "comment": "-",
            "recipe": "default",
            "prepare_recipe": "default",
            "state": state,
            "set_as_current": False
        }
    }
    headers = {"Authorization": "OAuth {}".format(token), "Content-Type": "application/json"}
    url = "https://nanny.yandex-team.ru/v2/services/{}/events/".format(id)
    r = requests.post(url, headers=headers, json=body, verify=False)
    r.raise_for_status()
    return r.json()


def post_set_current_snapshot(id, snapshot_id):
    body = {
        "serviceId": id,
        "snapshotId": snapshot_id
        }

    headers = {"Authorization": "OAuth {}".format(token), "Content-Type": "application/json"}
    url = "https://nanny.yandex-team.ru/api/repo/SetRuntimeSnapshotAsCurrent/"
    r = requests.post(url, headers=headers, json=body, verify=False)
    r.raise_for_status()
    return r.json()


def update_yav_deploy_conf(id, resource_id, task_id):
    runtime_attrs = get_service_attrs(id, "runtime_attrs")
    yav_deploy_conf = {
        "extract_path": "",
        "is_dynamic": False,
        "local_path": "yav-deploy.conf",
        "resource_id": resource_id,
        "resource_type": "BALANCER_L7_YAV_DEPLOY_CONF",
        "task_id": task_id,
        "task_type": "BUILD_BALANCER_CONFIGS_L7"
        }

    for i, item in enumerate(runtime_attrs['content']['resources']['sandbox_files']):
        if item.get("local_path") == "yav-deploy.conf":
            runtime_attrs['content']['resources']['sandbox_files'][i] = yav_deploy_conf
            break
    else:
        assert False, "Something went wrong, can't find yav-deploy.conf resource"

    response = put_service_attrs(id, "runtime_attrs", runtime_attrs, "Update yav-deploy.conf file with certificates from https://a.yandex-team.ru/review/2368993")
    post_set_snapshot_state_event(id, response["_id"], "PREPARED")
    post_set_current_snapshot(id, runtime_attrs["_id"])


def main():
    assert token, 'To get token use - http://nanny.yandex-team.ru/ui/#/oauth/ and dump to ~/.nanny_token or to NANNY_TOKEN env'

    svc_list = [
        'balancer_l7leveler_kubr_vla_experiment',
        'balancer_l7leveler_kubr_man',
        'balancer_l7leveler_kubr_sas',
        'balancer_l7leveler_kubr_vla',
        ]
    yav_deploy_conf = {
        "resource_id": "3047210148",
        "task_id": "1293632999"
        }

    log.info("Start snapshots generation with GS certificates:")
    for svc in svc_list:
        update_yav_deploy_conf(svc, yav_deploy_conf["resource_id"], yav_deploy_conf["task_id"])
        log.info("Create snapshot for {} service".format(svc))


if __name__ == "__main__":
    main()
