#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright (C) 2019 tribe29 GmbH - License: GNU General Public License v2
# This file is part of Checkmk (https://checkmk.com). It is subject to the terms and
# conditions defined in the file COPYING, which is part of this source code package.

import typing

LegacyMetricTuple = typing.Tuple[str, float, typing.Optional[float], typing.Optional[float],
                                 typing.Optional[float], typing.Optional[float]]


def parse_mrpe(info):
    PluginData = collections.namedtuple("PluginData", ("name", "state", "info"))

    parsed = {}
    for line in info:
        # New Linux agent sends (check_name) in first column. Stay
        # compatible with MRPE versions not providing this info
        if line[0].startswith("("):
            name = line[0].strip('()')
            line = line[1:]
        else:
            name = None

        if len(line) < 2:
            continue

        import urllib.parse
        item = urllib.parse.unquote(line[0])
        state = line[1]
        line = line[2:]

        try:
            state = int(state)
        except ValueError:
            pass

        if state not in (0, 1, 2, 3):
            line.insert(0, "Invalid plugin status '%s'. Output is:" % state)
            state = 3

        # convert to original format by joining and splitting at \1 (which replaced \n)
        info = " ".join(line).split("\1")

        dataset = PluginData(name, state, info)
        parsed.setdefault(item, []).append(dataset)

    return parsed


def _opt_float(string: str) -> typing.Optional[float]:
    try:
        return float(string)
    except ValueError:
        return None


def _strip_unit_float(string: str) -> float:
    """
        >>> _strip_unit_float("12.3 MB")
        12.3
    """
    for i in range(len(string), 0, -1):
        try:
            return float(string[:i])
        except ValueError:
            pass

    raise ValueError(f"invalid metric value {string!r}")


def parse_nagios_perfstring(perfinfo: str) -> LegacyMetricTuple:
    try:
        name, valuetxt = perfinfo.split("=", 1)
    except ValueError:
        raise ValueError(f"{perfinfo!r}")
    if valuetxt.startswith("U"):
        # Nagios perfstrings can start with a value 'U' to indicate an undefined value
        # see https://nagios-plugins.org/doc/guidelines.html#AEN200
        raise ValueError("Nagios style undefined value")
    values = valuetxt.split(";")

    # for the migrator: the code above ^^^^^ should go to a separate function

    # perfdata must not contain values with colons. So we split
    # these values and use the upper levels only.
    values = [v.split(':')[-1] for v in values][:5]
    value, warn, crit, min_, max_ = values + [""] * (5 - len(values))

    return (
        name,
        _strip_unit_float(value),
        _opt_float(warn),
        _opt_float(crit),
        _opt_float(min_),
        _opt_float(max_),
    )


def _output_metrics(perfdata: typing.Sequence[str]):
    for raw_metric in perfdata:
        try:
            yield 0, "", [parse_nagios_perfstring(raw_metric)]
        except ValueError as exc:
            yield 3, f"Undefined metric: {exc}", []


@get_parsed_item_data
def check_mrpe(_no_item, _no_params, data):
    # This check is cluster-aware. An item might be found
    # more than once. In that case we use the best of the
    # multiple statuses (Where OK < WARN < UNKNOWN < CRIT).
    dataset = min(data, key=lambda x: (0, 1, 3, 2)[x.state])

    # First line:  OUTPUT|PERFDATA
    parts = dataset.info[0].split("|", 1)
    output = [parts[0].strip()]
    if len(parts) > 1:
        perfdata = parts[1].strip().split()
    else:
        perfdata = []

    # Further lines
    now_comes_perfdata = False
    for line in dataset.info[1:]:
        if now_comes_perfdata:
            perfdata += line.split()
        else:
            parts = line.split("|", 1)
            output.append(parts[0].strip())
            if len(parts) > 1:
                perfdata += parts[1].strip().split()
                now_comes_perfdata = True

    yield dataset.state, "\n".join(output)

    yield from _output_metrics(perfdata)

    # name of check command needed for PNP to choose the correct template
    if dataset.name:
        yield 0, "\nCheck command used in metric system: %s" % dataset.name


check_info["mrpe"] = {
    'parse_function': parse_mrpe,
    'inventory_function': discover(),
    'check_function': check_mrpe,
    'service_description': '%s',
    'has_perfdata': True,
}
