#!/usr/bin/env python
import os
import sys
import urllib2
import json
import argparse

def nanny_get_active_conf(service_name, force=False):
    request = urllib2.Request("http://nanny.yandex-team.ru/v2/services/{}/current_state/".format(service_name), headers = {
        "Accept" : "application/json",
        "Authorization" : "OAuth " + os.environ.get("OAUTH_NANNY")
    })

    res = json.load(urllib2.urlopen(request))
    for snap in res["content"]["active_snapshots"]:
        if snap["state"] == "ACTIVE":
            return snap["conf_id"]
    if force:
        conf_ids = [snap["conf_id"] for snap in res["content"]["active_snapshots"]]
        if conf_ids:
            return sorted(conf_ids, reverse=True)[0]
    return None

def exit_with_error(msg, stdout_mode):
    if not stdout_mode:
        print >>sys.stderr, msg
    else:
        print "ERROR<{}>".format(msg)

    exit(1)

def print_help():
    print >>sys.stderr, "Usage: get_nanny_conf NANNY_SERVICE_NAME"

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description='Get CMS configuration from nanny service')
    parser.add_argument('service_name', help='Nanny service')
    parser.add_argument('-f', dest='force', action='store_true', help='If the service is updating, get any configuration')
    parser.add_argument('--stdout-error', action='store_true', help=argparse.SUPPRESS);
    args = parser.parse_args()

    try:
        nanny_active=nanny_get_active_conf(args.service_name, args.force)
    except Exception, e:
        exit_with_error("Cannot resolve service {}: [{}] {}".format(args.service_name, type(e).__name__, str(e)), args.stdout_error)

    if nanny_active is None:
        exit_with_error("Cannot find the active configuration (service is updating?)", args.stdout_error)

    print nanny_active
