#!/usr/bin/env python3

"""
Kuhn & Rueß GmbH
Consulting and Development
https://kuhn-ruess.de
"""

from sys import argv
from requests import post
from requests.auth import HTTPBasicAuth
from json import JSONDecodeError


class AgentJson():
    """
    Agent Json
    """

    map_states = {
        'OK': 0,
        'UP': 0,
        'WARN': 1,
        'WARNING': 1,
        'CRIT': 2,
        'CRITICAL': 2,
        'DOWN': 2,
        'UNKN': 3,
        'UNKNOWN': 3,
    }

    def __init__(self, api_host, user, password):
        """
        Init
        """
        self.api_host = api_host
        self.auth = None
        if user:
            self.auth = HTTPBasicAuth(user, password)

    def get_json(self):
        """
        Get JSON Stream
        """
        response = post(self.api_host, auth=self.auth, timeout=30)
        checks = response.json()['checks']

        print("<<<local>>>")
        seen_names = {}
        for check in checks:
            # Map the status string to a Checkmk state; everything we do not
            # know maps to UNKNOWN(3) instead of silently claiming CRIT.
            state = self.map_states.get(str(check['status']).upper(), 3)

            # Number repeated service names so duplicate keys stay discoverable
            # (first stays as is, the next ones become "<name> 2", "<name> 3").
            name = check['name']
            seen_names[name] = seen_names.get(name, 0) + 1
            service_name = name if seen_names[name] == 1 else f"{name} {seen_names[name]}"

            data = check.get('data', {})
            detail_lines = [f"{key}: {value}" for key, value in data.items()]

            if check.get('summary'):
                # Show the given summary on the first line and put the data
                # fields below it as multi-line details (\n separated).
                output = "\\n".join([str(check['summary'])] + detail_lines)
            else:
                output = ", ".join(detail_lines)

            print(f'{state} "{service_name}" - {output}')


if __name__ == "__main__":
    try:
        aj = AgentJson(argv[1], argv[2], argv[3])
        aj.get_json()
    except JSONDecodeError as error:
        print(f"Cannot parse API response: {error}")
