#!/usr/bin/env python
import collections
import os
import sys

import requests

try:
    import json
except ImportError:
    import simplejson as json


def die(messages):
    if type(messages) == 'string':
        die([messages])
    else:
        for message in messages:
            sys.stderr.write(message)
        sys.exit(1)


def read_config_json():
    config_file = os.environ['HOME'] + '/.ansible/perspective.json'
    if not os.path.exists(config_file):
        die("ERROR: config file %s not found\n" % config_file)
    try:
        fd = open(config_file, 'r')
        return json.loads(fd.read())
    except Exception as e:
        die("ERROR: failed to parse %s as JSON: %s\n" % (config_file, e))


def fetch_hosts(config_json):
    api_url = config_json['url'] if 'url' in config_json else 'http://localhost:8080/'
    query_url = api_url + "query"
    response = requests.post(query_url, json=[{
        "sql": "select name, addresses, fqdn from instances order by fqdn, name"
    }])
    if response.status_code != 200:
        die(
            "ERROR: failed to fetch data from %s, server returned: %d %s\n" %
                (query_url, response.status_code, response.reason)
        )
    return json.loads(response.text)


def to_json(in_dict):
    return json.dumps(in_dict, sort_keys=True)


def print_hosts(hosts_json):
    groups = collections.defaultdict(list)
    hostvars = {}
    all_hosts = []
    groups['_meta'] = {'hostvars': hostvars}
    groups['all'] = all_hosts
    if len(hosts_json) > 0:
        result = hosts_json[0]
        status = result["status"]
        if status == "success":
            data = result["data"]["row"]
            if data:
                for row in data:
                    name = row["value"][0]
                    addresses = row["value"][1]
                    fqdn = row["value"][2]
                    if (fqdn is None):
                        address = addresses.splitlines()[0]
                        hostvars[name] = {'short_name': name, 'ansible_host': address}
                    else:
                        all_hosts.append(fqdn)
                        hostvars[fqdn] = {'short_name': name}
                sys.stdout.write(to_json(groups))
        else:
            die("ERROR: SQL request error: %s\n" % (result["message"]))


def main():
    config_json = read_config_json()
    hosts_json = fetch_hosts(config_json)
    print_hosts(hosts_json)
    sys.exit(0)

if __name__ == '__main__':
    main()