import json
from operator import itemgetter
import sys
import urllib2
import urlparse


OK       = 0
WARN     = 1
CRITICAL = 2
UNKNOWN  = 3

STATUS_MAP = {
    "OK": OK,
    "WARN": WARN,
    "CRITICAL": CRITICAL,
    "UNKNOWN": UNKNOWN
}


def process_response(health):
    """Given a health resource response, return the most critical error value

    Also prepares a list of statuses, with the most critical ones first.
    """
    worst = OK
    statuses = []
    for key, value in health.items():
        if " " in value:
            str_status, msg = value.split(" ", 1)
        else:
            str_status, msg = value, ""
        status = STATUS_MAP[str_status]
        if status > worst:
            worst = status
        msg = '{} "{}": {}'.format(str_status, key, msg)
        statuses.append((status, key, msg))
    s = sorted(statuses, key=itemgetter(1))
    s = sorted(s, key=itemgetter(0), reverse=True)
    return worst, "\n".join(item[2] for item in s)


def check_status(mekansm_base):
    health_url = urlparse.urljoin(mekansm_base, "/health")
    try:
        f = urllib2.urlopen(health_url)
    except urllib2.URLError:
        return CRITICAL, "CRITICAL {} is down".format(mekansm_base)
    except Exception:
        return UNKNOWN, "Invalid Mekansm URL parameter"
    if f.getcode() != 200:
        return CRITICAL, "CRITICAL Got {} status in {}".format(
            f.getcode(), health_url)
    try:
        health = json.loads(f.read())
    except Exception:
        return CRITICAL, "CRITICAL Couldn't json parse {}".format(health_url)
    return process_response(health)

def main():
    args = sys.argv
    if len(args) != 2:
        status, msg = UNKNOWN, "UNKNOWN Invalid arguments"
    else:
        status, msg = check_status(args[1])
    sys.stdout.write(msg + "\n")
    sys.exit(status)


if __name__ == "__main__":
    sys.exit(main())
