#!/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 math


def parse_k8s_surge(value, total):
    """
    Returns the upper level for replicas which is considered critical
    (hence the +1 in the return value). Values may be given as an
    absolute number or in percent.
    """
    if isinstance(value, int):
        return value + total + 1
    percentage = 1.0 + float(value.rstrip('%')) / 100.0
    return math.ceil(percentage * total) + 1


def parse_k8s_unavailability(value, total):
    """
    Returns the lower level for replicas which is still considered ok.
    Values may be given as an absolute number or in percent.
    """
    if isinstance(value, int):
        return total - value
    percentage = 1.0 - float(value.rstrip('%')) / 100.0
    return math.floor(percentage * total)


def inventory_k8s_replicas(parsed):
    # the deployment must either be paused or return numbers for running pods
    if (parsed['ready_replicas'] is not None and
            parsed['replicas'] is not None) or parsed['paused']:
        yield (None, {})


def check_k8s_replicas(_no_item, _params, parsed):
    ready, total = parsed['ready_replicas'], parsed['replicas']
    paused, strategy = parsed['paused'], parsed['strategy_type']

    if total is None or ready is None:
        first_unavailable_time = get_item_state("unavailable")
        if first_unavailable_time:
            age = time.time() - first_unavailable_time
            if age > 600:  # setting 10 minutes as default threshold for missing replica data
                yield check_levels(
                    age,
                    None,
                    (None, 600),
                    human_readable_func=get_age_human_readable,
                    infoname="The replicas data has been missing",
                )
                return
        set_item_state("unavailable", time.time())
        raise MKCounterWrapped("The replicas data is currently unavailable")

    # previously missing but now complete data
    if get_item_state("unavailable"):
        set_item_state("unavailable", None)

    if paused or strategy == 'Recreate':
        crit, crit_lower = None, None
    elif strategy == 'RollingUpdate':
        crit = parse_k8s_surge(parsed['max_surge'], total)
        crit_lower = parse_k8s_unavailability(parsed['max_unavailable'], total)
    else:
        yield 3, "Unknown deployment strategy: %s" % strategy
        return

    state = 0
    infotext = "Ready: %s/%s" % (ready, total)
    if paused:
        infotext += ' (paused)'
    if crit is not None and ready >= crit:
        state = 2
        infotext += " (crit at %d)" % crit
    if crit_lower is not None and ready < crit_lower:
        state = 2
        infotext += " (crit below %d)" % crit_lower

    perfdata = [
        ('ready_replicas', ready, None, crit, 0, total),
        ('total_replicas', total),
    ]
    yield state, infotext, perfdata

    if strategy:
        strategy_infotext = "Strategy: %s" % parsed['strategy_type']
        if strategy == 'RollingUpdate':
            strategy_infotext += " (max unavailable: %s, max surge: %s)" % (
                parsed['max_unavailable'],
                parsed['max_surge'],
            )
        yield 0, strategy_infotext


check_info['k8s_replicas'] = {
    # section already migrated
    'inventory_function': inventory_k8s_replicas,
    'check_function': check_k8s_replicas,
    'service_description': 'Replicas',
}
