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

# NOTE: Careful when replacing the *-import below with a more specific import. This can cause
# problems because it might remove variables from the check-context which are necessary for
# resolving legacy discovery results such as [("SUMMARY", "diskstat_default_levels")]. Furthermore,
# it might also remove variables needed for accessing discovery rulesets.
from cmk.base.check_legacy_includes.aws import *  # pylint: disable=wildcard-import,unused-wildcard-import


def check_aws_wafv2_summary(item, params, parsed):

    web_acls_by_region: Dict[str, Dict] = {}

    for web_acl in parsed:
        try:
            region_key = AWSRegions[web_acl["Region"]]
        except KeyError:
            region_key = web_acl["Region"]  # CloudFront
        web_acls_by_region.setdefault(region_key, {})[web_acl["Name"]] = web_acl

    regions_sorted = sorted(web_acls_by_region.keys())
    long_output = []

    yield 0, "Total number of Web ACLs: %s" % len(parsed)

    for region in regions_sorted:
        web_acls_region = web_acls_by_region[region]
        yield 0, "%s: %s" % (region, len(web_acls_region))

        web_acl_names_sorted = sorted(web_acls_region.keys())
        long_output.append("%s:" % region)

        for web_acl_name in web_acl_names_sorted:
            web_acl = web_acls_region[web_acl_name]

            description = web_acl["Description"]
            if not description:
                description = "[no description]"

            long_output.append(
                "%s -- Description: %s, Number of rules and rule groups: %s"
                % (web_acl_name, description, len(web_acl["Rules"]))
            )

    if long_output:
        yield 0, "\n%s" % "\n".join(long_output)


check_info["aws_wafv2_summary"] = {
    "parse_function": parse_aws,
    "inventory_function": discover_single,
    "check_function": check_aws_wafv2_summary,
    "service_description": "AWS/WAFV2 Summary",
}
