#!/usr/bin/python
from __future__ import absolute_import, division, print_function

# Copyright: (c) 2022 Fortinet
# GNU General Public License v3.0+ (see LICENSE or https://www.gnu.org/licenses/gpl-3.0.txt)
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.

__metaclass__ = type

ANSIBLE_METADATA = {
    "status": ["preview"],
    "supported_by": "community",
    "metadata_version": "1.1",
}

DOCUMENTATION = """
---
module: fortios_system_npu
short_description: Configure NPU attributes in Fortinet's FortiOS and FortiGate.
description:
    - This module is able to configure a FortiGate or FortiOS (FOS) device by allowing the
      user to set and modify system feature and npu category.
      Examples include all parameters and values need to be adjusted to datasources before usage.
      Tested with FOS v6.0.0
version_added: "2.0.0"
author:
    - Link Zheng (@chillancezen)
    - Jie Xue (@JieX19)
    - Hongbin Lu (@fgtdev-hblu)
    - Frank Shen (@frankshen01)
    - Miguel Angel Munoz (@mamunozgonzalez)
    - Nicolas Thomas (@thomnico)
notes:
    - Legacy fortiosapi has been deprecated, httpapi is the preferred way to run playbooks

requirements:
    - ansible>=2.14
options:
    access_token:
        description:
            - Token-based authentication.
              Generated from GUI of Fortigate.
        type: str
        required: false
    enable_log:
        description:
            - Enable/Disable logging for task.
        type: bool
        required: false
        default: false
    vdom:
        description:
            - Virtual domain, among those defined previously. A vdom is a
              virtual instance of the FortiGate that can be configured and
              used as a different unit.
        type: str
        default: root
    member_path:
        type: str
        description:
            - Member attribute path to operate on.
            - Delimited by a slash character if there are more than one attribute.
            - Parameter marked with member_path is legitimate for doing member operation.
    member_state:
        type: str
        description:
            - Add or delete a member under specified attribute path.
            - When member_state is specified, the state option is ignored.
        choices:
            - 'present'
            - 'absent'

    system_npu:
        description:
            - Configure NPU attributes.
        default: null
        type: dict
        suboptions:
            capwap_offload:
                description:
                    - Enable/disable offloading managed FortiAP and FortiLink CAPWAP sessions.
                type: str
                choices:
                    - 'enable'
                    - 'disable'
            dedicated_management_affinity:
                description:
                    - Affinity setting for management daemons (hexadecimal value up to 256 bits in the format of xxxxxxxxxxxxxxxx).
                type: str
            dedicated_management_cpu:
                description:
                    - Enable to dedicate one CPU for GUI and CLI connections when NPs are busy.
                type: str
                choices:
                    - 'enable'
                    - 'disable'
            fastpath:
                description:
                    - Enable/disable NP6 offloading (also called fast path).
                type: str
                choices:
                    - 'disable'
                    - 'enable'
            gtp_enhanced_cpu_range:
                description:
                    - GTP enhanced CPU range option.
                type: str
                choices:
                    - '0'
                    - '1'
                    - '2'
            gtp_enhanced_mode:
                description:
                    - Enable/disable GTP enhanced mode.
                type: str
                choices:
                    - 'enable'
                    - 'disable'
            intf_shaping_offload:
                description:
                    - Enable/disable NPU offload when doing interface-based traffic shaping according to the egress-shaping-profile.
                type: str
                choices:
                    - 'enable'
                    - 'disable'
            ipsec_dec_subengine_mask:
                description:
                    - IPsec decryption subengine mask (0x1 - 0xff).
                type: str
            ipsec_enc_subengine_mask:
                description:
                    - IPsec encryption subengine mask (0x1 - 0xff).
                type: str
            ipsec_inbound_cache:
                description:
                    - Enable/disable IPsec inbound cache for anti-replay.
                type: str
                choices:
                    - 'enable'
                    - 'disable'
            ipsec_mtu_override:
                description:
                    - Enable/disable NP6 IPsec MTU override.
                type: str
                choices:
                    - 'disable'
                    - 'enable'
            ipsec_over_vlink:
                description:
                    - Enable/disable IPsec over vlink.
                type: str
                choices:
                    - 'enable'
                    - 'disable'
            isf_np_queues:
                description:
                    - Configure queues of switch port connected to NP6 XAUI on ingress path.
                type: dict
                suboptions:
                    cos0:
                        description:
                            - CoS profile name for CoS 0. Source system.isf-queue-profile.name.
                        type: str
                    cos1:
                        description:
                            - CoS profile name for CoS 1. Source system.isf-queue-profile.name.
                        type: str
                    cos2:
                        description:
                            - CoS profile name for CoS 2. Source system.isf-queue-profile.name.
                        type: str
                    cos3:
                        description:
                            - CoS profile name for CoS 3. Source system.isf-queue-profile.name.
                        type: str
                    cos4:
                        description:
                            - CoS profile name for CoS 4. Source system.isf-queue-profile.name.
                        type: str
                    cos5:
                        description:
                            - CoS profile name for CoS 5. Source system.isf-queue-profile.name.
                        type: str
                    cos6:
                        description:
                            - CoS profile name for CoS 6. Source system.isf-queue-profile.name.
                        type: str
                    cos7:
                        description:
                            - CoS profile name for CoS 7. Source system.isf-queue-profile.name.
                        type: str
            lag_out_port_select:
                description:
                    - Enable/disable LAG outgoing port selection based on incoming traffic port.
                type: str
                choices:
                    - 'disable'
                    - 'enable'
            mcast_session_accounting:
                description:
                    - Enable/disable traffic accounting for each multicast session through TAE counter.
                type: str
                choices:
                    - 'tpe-based'
                    - 'session-based'
                    - 'disable'
            port_cpu_map:
                description:
                    - Configure NPU interface to CPU core mapping.
                type: list
                elements: dict
                suboptions:
                    cpu_core:
                        description:
                            - The CPU core to map to an interface.
                        type: str
                    interface:
                        description:
                            - The interface to map to a CPU core.
                        required: true
                        type: str
            port_npu_map:
                description:
                    - Configure port to NPU group mapping.
                type: list
                elements: dict
                suboptions:
                    interface:
                        description:
                            - Set NPU interface port for NPU group mapping.
                        required: true
                        type: str
                    npu_group_index:
                        description:
                            - Mapping NPU group index.
                        type: int
            priority_protocol:
                description:
                    - Configure NPU priority protocol.
                type: dict
                suboptions:
                    bfd:
                        description:
                            - Enable/disable NPU BFD priority protocol.
                        type: str
                        choices:
                            - 'enable'
                            - 'disable'
                    bgp:
                        description:
                            - Enable/disable NPU BGP priority protocol.
                        type: str
                        choices:
                            - 'enable'
                            - 'disable'
                    slbc:
                        description:
                            - Enable/disable NPU SLBC priority protocol.
                        type: str
                        choices:
                            - 'enable'
                            - 'disable'
            qos_mode:
                description:
                    - QoS mode on switch and NP.
                type: str
                choices:
                    - 'disable'
                    - 'priority'
                    - 'round-robin'
            rdp_offload:
                description:
                    - Enable/disable RDP offload.
                type: str
                choices:
                    - 'enable'
                    - 'disable'
            session_denied_offload:
                description:
                    - Enable/disable offloading of denied sessions. Requires ses-denied-traffic to be set.
                type: str
                choices:
                    - 'disable'
                    - 'enable'
            sse_backpressure:
                description:
                    - Enable/disable SSE backpressure.
                type: str
                choices:
                    - 'enable'
                    - 'disable'
            strip_clear_text_padding:
                description:
                    - Enable/disable stripping clear text padding.
                type: str
                choices:
                    - 'enable'
                    - 'disable'
            strip_esp_padding:
                description:
                    - Enable/disable stripping ESP padding.
                type: str
                choices:
                    - 'enable'
                    - 'disable'
            sw_eh_hash:
                description:
                    - Configure switch enhanced hashing.
                type: dict
                suboptions:
                    computation:
                        description:
                            - Set hashing computation.
                        type: str
                        choices:
                            - 'xor16'
                            - 'xor8'
                            - 'xor4'
                            - 'crc16'
                    destination_ip_lower_16:
                        description:
                            - Include/exclude destination IP address lower 16 bits.
                        type: str
                        choices:
                            - 'include'
                            - 'exclude'
                    destination_ip_upper_16:
                        description:
                            - Include/exclude destination IP address upper 16 bits.
                        type: str
                        choices:
                            - 'include'
                            - 'exclude'
                    destination_port:
                        description:
                            - Include/exclude destination port if TCP/UDP.
                        type: str
                        choices:
                            - 'include'
                            - 'exclude'
                    ip_protocol:
                        description:
                            - Include/exclude IP protocol.
                        type: str
                        choices:
                            - 'include'
                            - 'exclude'
                    netmask_length:
                        description:
                            - Network mask length.
                        type: int
                    source_ip_lower_16:
                        description:
                            - Include/exclude source IP address lower 16 bits.
                        type: str
                        choices:
                            - 'include'
                            - 'exclude'
                    source_ip_upper_16:
                        description:
                            - Include/exclude source IP address upper 16 bits.
                        type: str
                        choices:
                            - 'include'
                            - 'exclude'
                    source_port:
                        description:
                            - Include/exclude source port if TCP/UDP.
                        type: str
                        choices:
                            - 'include'
                            - 'exclude'
            sw_np_bandwidth:
                description:
                    - Bandwidth from switch to NP.
                type: str
                choices:
                    - '0G'
                    - '2G'
                    - '4G'
                    - '5G'
                    - '6G'
                    - '7G'
                    - '8G'
                    - '9G'
            sw_tr_hash:
                description:
                    - Configure switch traditional hashing.
                type: dict
                suboptions:
                    draco15:
                        description:
                            - Enable/disable DRACO15 hashing.
                        type: str
                        choices:
                            - 'enable'
                            - 'disable'
                    tcp_udp_port:
                        description:
                            - Include/exclude TCP/UDP source and destination port for unicast trunk traffic.
                        type: str
                        choices:
                            - 'include'
                            - 'exclude'
            uesp_offload:
                description:
                    - Enable/disable UDP-encapsulated ESP offload .
                type: str
                choices:
                    - 'enable'
                    - 'disable'
"""

EXAMPLES = """
- name: Configure NPU attributes.
  fortinet.fortios.fortios_system_npu:
      vdom: "{{ vdom }}"
      system_npu:
          capwap_offload: "enable"
          dedicated_management_affinity: "<your_own_value>"
          dedicated_management_cpu: "enable"
          fastpath: "disable"
          gtp_enhanced_cpu_range: "0"
          gtp_enhanced_mode: "enable"
          intf_shaping_offload: "enable"
          ipsec_dec_subengine_mask: "<your_own_value>"
          ipsec_enc_subengine_mask: "<your_own_value>"
          ipsec_inbound_cache: "enable"
          ipsec_mtu_override: "disable"
          ipsec_over_vlink: "enable"
          isf_np_queues:
              cos0: "<your_own_value> (source system.isf-queue-profile.name)"
              cos1: "<your_own_value> (source system.isf-queue-profile.name)"
              cos2: "<your_own_value> (source system.isf-queue-profile.name)"
              cos3: "<your_own_value> (source system.isf-queue-profile.name)"
              cos4: "<your_own_value> (source system.isf-queue-profile.name)"
              cos5: "<your_own_value> (source system.isf-queue-profile.name)"
              cos6: "<your_own_value> (source system.isf-queue-profile.name)"
              cos7: "<your_own_value> (source system.isf-queue-profile.name)"
          lag_out_port_select: "disable"
          mcast_session_accounting: "tpe-based"
          port_cpu_map:
              -
                  cpu_core: "<your_own_value>"
                  interface: "<your_own_value>"
          port_npu_map:
              -
                  interface: "<your_own_value>"
                  npu_group_index: "0"
          priority_protocol:
              bfd: "enable"
              bgp: "enable"
              slbc: "enable"
          qos_mode: "disable"
          rdp_offload: "enable"
          session_denied_offload: "disable"
          sse_backpressure: "enable"
          strip_clear_text_padding: "enable"
          strip_esp_padding: "enable"
          sw_eh_hash:
              computation: "xor16"
              destination_ip_lower_16: "include"
              destination_ip_upper_16: "include"
              destination_port: "include"
              ip_protocol: "include"
              netmask_length: "32"
              source_ip_lower_16: "include"
              source_ip_upper_16: "include"
              source_port: "include"
          sw_np_bandwidth: "0G"
          sw_tr_hash:
              draco15: "enable"
              tcp_udp_port: "include"
          uesp_offload: "enable"
"""

RETURN = """
build:
  description: Build number of the fortigate image
  returned: always
  type: str
  sample: '1547'
http_method:
  description: Last method used to provision the content into FortiGate
  returned: always
  type: str
  sample: 'PUT'
http_status:
  description: Last result given by FortiGate on last operation applied
  returned: always
  type: str
  sample: "200"
mkey:
  description: Master key (id) used in the last call to FortiGate
  returned: success
  type: str
  sample: "id"
name:
  description: Name of the table used to fulfill the request
  returned: always
  type: str
  sample: "urlfilter"
path:
  description: Path of the table used to fulfill the request
  returned: always
  type: str
  sample: "webfilter"
revision:
  description: Internal revision number
  returned: always
  type: str
  sample: "17.0.2.10658"
serial:
  description: Serial number of the unit
  returned: always
  type: str
  sample: "FGVMEVYYQT3AB5352"
status:
  description: Indication of the operation's result
  returned: always
  type: str
  sample: "success"
vdom:
  description: Virtual domain used
  returned: always
  type: str
  sample: "root"
version:
  description: Version of the FortiGate
  returned: always
  type: str
  sample: "v5.6.3"
"""
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.connection import Connection
from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.fortios import (
    FortiOSHandler,
)
from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.fortios import (
    check_legacy_fortiosapi,
)
from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.fortios import (
    schema_to_module_spec,
)
from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.fortios import (
    check_schema_versioning,
)
from ansible_collections.fortinet.fortios.plugins.module_utils.fortimanager.common import (
    FAIL_SOCKET_MSG,
)
from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.data_post_processor import (
    remove_invalid_fields,
)


def filter_system_npu_data(json):
    option_list = [
        "capwap_offload",
        "dedicated_management_affinity",
        "dedicated_management_cpu",
        "fastpath",
        "gtp_enhanced_cpu_range",
        "gtp_enhanced_mode",
        "intf_shaping_offload",
        "ipsec_dec_subengine_mask",
        "ipsec_enc_subengine_mask",
        "ipsec_inbound_cache",
        "ipsec_mtu_override",
        "ipsec_over_vlink",
        "isf_np_queues",
        "lag_out_port_select",
        "mcast_session_accounting",
        "port_cpu_map",
        "port_npu_map",
        "priority_protocol",
        "qos_mode",
        "rdp_offload",
        "session_denied_offload",
        "sse_backpressure",
        "strip_clear_text_padding",
        "strip_esp_padding",
        "sw_eh_hash",
        "sw_np_bandwidth",
        "sw_tr_hash",
        "uesp_offload",
    ]

    json = remove_invalid_fields(json)
    dictionary = {}

    for attribute in option_list:
        if attribute in json and json[attribute] is not None:
            dictionary[attribute] = json[attribute]

    return dictionary


def underscore_to_hyphen(data):
    if isinstance(data, list):
        for i, elem in enumerate(data):
            data[i] = underscore_to_hyphen(elem)
    elif isinstance(data, dict):
        new_data = {}
        for k, v in data.items():
            new_data[k.replace("_", "-")] = underscore_to_hyphen(v)
        data = new_data

    return data


def system_npu(data, fos):
    vdom = data["vdom"]
    system_npu_data = data["system_npu"]
    filtered_data = underscore_to_hyphen(filter_system_npu_data(system_npu_data))

    return fos.set("system", "npu", data=filtered_data, vdom=vdom)


def is_successful_status(resp):
    return (
        "status" in resp
        and resp["status"] == "success"
        or "http_status" in resp
        and resp["http_status"] == 200
        or "http_method" in resp
        and resp["http_method"] == "DELETE"
        and resp["http_status"] == 404
    )


def fortios_system(data, fos):
    fos.do_member_operation("system", "npu")
    if data["system_npu"]:
        resp = system_npu(data, fos)
    else:
        fos._module.fail_json(msg="missing task body: %s" % ("system_npu"))

    return (
        not is_successful_status(resp),
        is_successful_status(resp)
        and (resp["revision_changed"] if "revision_changed" in resp else True),
        resp,
        {},
    )


versioned_schema = {
    "v_range": [["v6.0.0", ""]],
    "type": "dict",
    "children": {
        "dedicated_management_cpu": {
            "v_range": [["v6.0.0", ""]],
            "type": "string",
            "options": [{"value": "enable"}, {"value": "disable"}],
        },
        "dedicated_management_affinity": {
            "v_range": [["v7.0.1", ""]],
            "type": "string",
        },
        "port_cpu_map": {
            "type": "list",
            "elements": "dict",
            "children": {
                "interface": {
                    "v_range": [
                        ["v6.4.0", "v6.4.0"],
                        ["v7.2.0", "v7.2.0"],
                        ["v7.4.0", ""],
                    ],
                    "type": "string",
                    "required": True,
                },
                "cpu_core": {
                    "v_range": [
                        ["v6.4.0", "v6.4.0"],
                        ["v7.2.0", "v7.2.0"],
                        ["v7.4.0", ""],
                    ],
                    "type": "string",
                },
            },
            "v_range": [["v6.4.0", "v6.4.0"], ["v7.2.0", "v7.2.0"], ["v7.4.0", ""]],
        },
        "fastpath": {
            "v_range": [["v6.0.0", ""]],
            "type": "string",
            "options": [{"value": "disable"}, {"value": "enable"}],
        },
        "capwap_offload": {
            "v_range": [["v6.0.0", ""]],
            "type": "string",
            "options": [{"value": "enable"}, {"value": "disable"}],
        },
        "ipsec_enc_subengine_mask": {"v_range": [["v6.0.0", ""]], "type": "string"},
        "ipsec_dec_subengine_mask": {"v_range": [["v6.0.0", ""]], "type": "string"},
        "sw_np_bandwidth": {
            "v_range": [["v6.2.0", ""]],
            "type": "string",
            "options": [
                {"value": "0G"},
                {"value": "2G"},
                {"value": "4G"},
                {"value": "5G"},
                {"value": "6G"},
                {"value": "7G", "v_range": [["v7.4.0", ""]]},
                {"value": "8G", "v_range": [["v7.4.0", ""]]},
                {"value": "9G", "v_range": [["v7.4.0", ""]]},
            ],
        },
        "gtp_enhanced_mode": {
            "v_range": [["v6.0.0", ""]],
            "type": "string",
            "options": [{"value": "enable"}, {"value": "disable"}],
        },
        "gtp_enhanced_cpu_range": {
            "v_range": [["v6.0.0", ""]],
            "type": "string",
            "options": [{"value": "0"}, {"value": "1"}, {"value": "2"}],
        },
        "intf_shaping_offload": {
            "v_range": [["v6.4.0", ""]],
            "type": "string",
            "options": [{"value": "enable"}, {"value": "disable"}],
        },
        "strip_esp_padding": {
            "v_range": [["v6.0.0", ""]],
            "type": "string",
            "options": [{"value": "enable"}, {"value": "disable"}],
        },
        "strip_clear_text_padding": {
            "v_range": [["v6.0.0", ""]],
            "type": "string",
            "options": [{"value": "enable"}, {"value": "disable"}],
        },
        "ipsec_inbound_cache": {
            "v_range": [["v6.2.0", ""]],
            "type": "string",
            "options": [{"value": "enable"}, {"value": "disable"}],
        },
        "sse_backpressure": {
            "v_range": [["v6.0.0", ""]],
            "type": "string",
            "options": [{"value": "enable"}, {"value": "disable"}],
        },
        "rdp_offload": {
            "v_range": [["v6.0.0", ""]],
            "type": "string",
            "options": [{"value": "enable"}, {"value": "disable"}],
        },
        "ipsec_over_vlink": {
            "v_range": [["v6.0.0", ""]],
            "type": "string",
            "options": [{"value": "enable"}, {"value": "disable"}],
        },
        "uesp_offload": {
            "v_range": [["v7.0.0", ""]],
            "type": "string",
            "options": [{"value": "enable"}, {"value": "disable"}],
        },
        "qos_mode": {
            "v_range": [["v6.4.0", "v6.4.0"], ["v7.2.0", "v7.2.0"], ["v7.4.0", ""]],
            "type": "string",
            "options": [
                {"value": "disable"},
                {"value": "priority"},
                {"value": "round-robin"},
            ],
        },
        "isf_np_queues": {
            "v_range": [["v6.4.0", "v6.4.0"], ["v7.2.0", "v7.2.0"], ["v7.4.0", ""]],
            "type": "dict",
            "children": {
                "cos0": {
                    "v_range": [
                        ["v6.4.0", "v6.4.0"],
                        ["v7.2.0", "v7.2.0"],
                        ["v7.4.0", ""],
                    ],
                    "type": "string",
                },
                "cos1": {
                    "v_range": [
                        ["v6.4.0", "v6.4.0"],
                        ["v7.2.0", "v7.2.0"],
                        ["v7.4.0", ""],
                    ],
                    "type": "string",
                },
                "cos2": {
                    "v_range": [
                        ["v6.4.0", "v6.4.0"],
                        ["v7.2.0", "v7.2.0"],
                        ["v7.4.0", ""],
                    ],
                    "type": "string",
                },
                "cos3": {
                    "v_range": [
                        ["v6.4.0", "v6.4.0"],
                        ["v7.2.0", "v7.2.0"],
                        ["v7.4.0", ""],
                    ],
                    "type": "string",
                },
                "cos4": {
                    "v_range": [
                        ["v6.4.0", "v6.4.0"],
                        ["v7.2.0", "v7.2.0"],
                        ["v7.4.0", ""],
                    ],
                    "type": "string",
                },
                "cos5": {
                    "v_range": [
                        ["v6.4.0", "v6.4.0"],
                        ["v7.2.0", "v7.2.0"],
                        ["v7.4.0", ""],
                    ],
                    "type": "string",
                },
                "cos6": {
                    "v_range": [
                        ["v6.4.0", "v6.4.0"],
                        ["v7.2.0", "v7.2.0"],
                        ["v7.4.0", ""],
                    ],
                    "type": "string",
                },
                "cos7": {
                    "v_range": [
                        ["v6.4.0", "v6.4.0"],
                        ["v7.2.0", "v7.2.0"],
                        ["v7.4.0", ""],
                    ],
                    "type": "string",
                },
            },
        },
        "mcast_session_accounting": {
            "v_range": [
                ["v6.0.0", "v6.0.0"],
                ["v6.0.11", "v6.2.0"],
                ["v6.2.5", "v6.2.7"],
                ["v6.4.4", ""],
            ],
            "type": "string",
            "options": [
                {"value": "tpe-based"},
                {"value": "session-based"},
                {"value": "disable"},
            ],
        },
        "ipsec_mtu_override": {
            "v_range": [["v6.2.0", "v6.2.0"], ["v6.2.7", "v6.2.7"], ["v6.4.4", ""]],
            "type": "string",
            "options": [{"value": "disable"}, {"value": "enable"}],
        },
        "lag_out_port_select": {
            "v_range": [["v6.2.0", "v6.2.7"], ["v6.4.1", ""]],
            "type": "string",
            "options": [{"value": "disable"}, {"value": "enable"}],
        },
        "sw_eh_hash": {
            "v_range": [["v7.2.0", "v7.2.0"], ["v7.4.0", ""]],
            "type": "dict",
            "children": {
                "computation": {
                    "v_range": [["v7.2.0", "v7.2.0"], ["v7.4.0", ""]],
                    "type": "string",
                    "options": [
                        {"value": "xor16"},
                        {"value": "xor8"},
                        {"value": "xor4"},
                        {"value": "crc16"},
                    ],
                },
                "ip_protocol": {
                    "v_range": [["v7.2.0", "v7.2.0"], ["v7.4.0", ""]],
                    "type": "string",
                    "options": [{"value": "include"}, {"value": "exclude"}],
                },
                "source_ip_upper_16": {
                    "v_range": [["v7.2.0", "v7.2.0"], ["v7.4.0", ""]],
                    "type": "string",
                    "options": [{"value": "include"}, {"value": "exclude"}],
                },
                "source_ip_lower_16": {
                    "v_range": [["v7.2.0", "v7.2.0"], ["v7.4.0", ""]],
                    "type": "string",
                    "options": [{"value": "include"}, {"value": "exclude"}],
                },
                "destination_ip_upper_16": {
                    "v_range": [["v7.2.0", "v7.2.0"], ["v7.4.0", ""]],
                    "type": "string",
                    "options": [{"value": "include"}, {"value": "exclude"}],
                },
                "destination_ip_lower_16": {
                    "v_range": [["v7.2.0", "v7.2.0"], ["v7.4.0", ""]],
                    "type": "string",
                    "options": [{"value": "include"}, {"value": "exclude"}],
                },
                "source_port": {
                    "v_range": [["v7.2.0", "v7.2.0"], ["v7.4.0", ""]],
                    "type": "string",
                    "options": [{"value": "include"}, {"value": "exclude"}],
                },
                "destination_port": {
                    "v_range": [["v7.2.0", "v7.2.0"], ["v7.4.0", ""]],
                    "type": "string",
                    "options": [{"value": "include"}, {"value": "exclude"}],
                },
                "netmask_length": {
                    "v_range": [["v7.2.0", "v7.2.0"], ["v7.4.0", ""]],
                    "type": "integer",
                },
            },
        },
        "sw_tr_hash": {
            "v_range": [["v7.4.0", ""]],
            "type": "dict",
            "children": {
                "draco15": {
                    "v_range": [["v7.4.0", ""]],
                    "type": "string",
                    "options": [{"value": "enable"}, {"value": "disable"}],
                },
                "tcp_udp_port": {
                    "v_range": [["v7.4.0", ""]],
                    "type": "string",
                    "options": [{"value": "include"}, {"value": "exclude"}],
                },
            },
        },
        "session_denied_offload": {
            "v_range": [["v7.0.0", ""]],
            "type": "string",
            "options": [{"value": "disable"}, {"value": "enable"}],
        },
        "priority_protocol": {
            "v_range": [["v6.0.0", "v6.0.0"], ["v6.0.11", ""]],
            "type": "dict",
            "children": {
                "bgp": {
                    "v_range": [["v6.0.0", "v6.0.0"], ["v6.0.11", ""]],
                    "type": "string",
                    "options": [{"value": "enable"}, {"value": "disable"}],
                },
                "slbc": {
                    "v_range": [["v6.0.0", "v6.0.0"], ["v6.0.11", ""]],
                    "type": "string",
                    "options": [{"value": "enable"}, {"value": "disable"}],
                },
                "bfd": {
                    "v_range": [["v6.0.0", "v6.0.0"], ["v6.0.11", ""]],
                    "type": "string",
                    "options": [{"value": "enable"}, {"value": "disable"}],
                },
            },
        },
        "port_npu_map": {
            "type": "list",
            "elements": "dict",
            "children": {
                "interface": {
                    "v_range": [
                        ["v6.0.0", "v6.2.7"],
                        ["v6.4.1", "v7.0.12"],
                        ["v7.2.1", "v7.2.4"],
                    ],
                    "type": "string",
                    "required": True,
                },
                "npu_group_index": {
                    "v_range": [
                        ["v6.0.0", "v6.2.7"],
                        ["v6.4.1", "v7.0.12"],
                        ["v7.2.1", "v7.2.4"],
                    ],
                    "type": "integer",
                },
            },
            "v_range": [
                ["v6.0.0", "v6.2.7"],
                ["v6.4.1", "v7.0.12"],
                ["v7.2.1", "v7.2.4"],
            ],
        },
    },
}


def main():
    module_spec = schema_to_module_spec(versioned_schema)
    mkeyname = None
    fields = {
        "access_token": {"required": False, "type": "str", "no_log": True},
        "enable_log": {"required": False, "type": "bool", "default": False},
        "vdom": {"required": False, "type": "str", "default": "root"},
        "member_path": {"required": False, "type": "str"},
        "member_state": {
            "type": "str",
            "required": False,
            "choices": ["present", "absent"],
        },
        "system_npu": {
            "required": False,
            "type": "dict",
            "default": None,
            "options": {},
        },
    }
    for attribute_name in module_spec["options"]:
        fields["system_npu"]["options"][attribute_name] = module_spec["options"][
            attribute_name
        ]
        if mkeyname and mkeyname == attribute_name:
            fields["system_npu"]["options"][attribute_name]["required"] = True

    module = AnsibleModule(argument_spec=fields, supports_check_mode=False)
    check_legacy_fortiosapi(module)

    is_error = False
    has_changed = False
    result = None
    diff = None

    versions_check_result = None
    if module._socket_path:
        connection = Connection(module._socket_path)
        if "access_token" in module.params:
            connection.set_option("access_token", module.params["access_token"])

        if "enable_log" in module.params:
            connection.set_option("enable_log", module.params["enable_log"])
        else:
            connection.set_option("enable_log", False)
        fos = FortiOSHandler(connection, module, mkeyname)
        versions_check_result = check_schema_versioning(
            fos, versioned_schema, "system_npu"
        )

        is_error, has_changed, result, diff = fortios_system(module.params, fos)

    else:
        module.fail_json(**FAIL_SOCKET_MSG)

    if versions_check_result and versions_check_result["matched"] is False:
        module.warn(
            "Ansible has detected version mismatch between FortOS system and your playbook, see more details by specifying option -vvv"
        )

    if not is_error:
        if versions_check_result and versions_check_result["matched"] is False:
            module.exit_json(
                changed=has_changed,
                version_check_warning=versions_check_result,
                meta=result,
                diff=diff,
            )
        else:
            module.exit_json(changed=has_changed, meta=result, diff=diff)
    else:
        if versions_check_result and versions_check_result["matched"] is False:
            module.fail_json(
                msg="Error in repo",
                version_check_warning=versions_check_result,
                meta=result,
            )
        else:
            module.fail_json(msg="Error in repo", meta=result)


if __name__ == "__main__":
    main()
