# Copyright 2022-2024 ETSI OSG/SDG TeraFlowSDN (TFS) (https://tfs.etsi.org/)
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import json
import logging
from typing import Any, List, Optional, Tuple, TypedDict, Union

from deepdiff import DeepDiff

from common.DeviceTypes import DeviceTypeEnum
from common.method_wrappers.Decorator import MetricsPool, metered_subclass_method
from common.proto.context_pb2 import (
    ConfigRule,
    Device,
    DeviceId,
    Service,
    ServiceConfig,
)
from common.tools.object_factory.Device import json_device_id
from common.type_checkers.Checkers import chk_type
from service.service.service_handler_api._ServiceHandler import _ServiceHandler
from service.service.service_handler_api.SettingsHandler import SettingsHandler
from service.service.service_handler_api.Tools import (
    get_device_endpoint_uuids,
    get_endpoint_matching,
)
from service.service.task_scheduler.TaskExecutor import TaskExecutor

from .ConfigRules import setup_config_rules, teardown_config_rules

RUNNING_RESOURCE_KEY = "running_ietf_slice"
CANDIDATE_RESOURCE_KEY = "candidate_ietf_slice"
MTU = 1500

LOGGER = logging.getLogger(__name__)

METRICS_POOL = MetricsPool("Service", "Handler", labels={"handler": "l3nm_ietf_l3vpn"})


class LANPrefixesDict(TypedDict):
    lan: str
    lan_tag: str


class Ipv4Info(TypedDict):
    src_lan: str
    dst_lan: str
    src_port: str
    dst_port: str
    vlan: str


class QoSInfo(TypedDict):
    src_qos_profile_latency: int
    src_input_bw: int
    src_output_bw: int
    dst_qos_profile_latency: int
    dst_input_bw: int
    dst_output_bw: int


def extract_qos_info_from_connection_group(
    src_sdp_id: str, dst_sdp_id: str, connectivity_constructs: dict
) -> QoSInfo:
    def extract_qos_info(cc: dict) -> Tuple[int, int]:
        for metric_bound in cc["service-slo-sle-policy"]["slo-policy"]["metric-bound"]:
            if (
                metric_bound["metric-type"]
                == "ietf-network-slice-service:one-way-delay-maximum"
                and metric_bound["metric-unit"] == "milliseconds"
            ):
                max_delay = int(metric_bound["bound"])
            elif (
                metric_bound["metric-type"]
                == "ietf-network-slice-service:one-way-bandwidth"
                and metric_bound["metric-unit"] == "Mbps"
            ):
                bandwidth = int(metric_bound["bound"]) * 1e6
        return max_delay, bandwidth

    src_cc = next(
        cc
        for cc in connectivity_constructs
        if cc["p2p-sender-sdp"] == src_sdp_id and cc["p2p-receiver-sdp"] == dst_sdp_id
    )
    dst_cc = next(
        cc
        for cc in connectivity_constructs
        if cc["p2p-sender-sdp"] == dst_sdp_id and cc["p2p-receiver-sdp"] == src_sdp_id
    )
    src_max_delay, src_bandwidth = extract_qos_info(src_cc)
    dst_max_delay, dst_bandwidth = extract_qos_info(dst_cc)
    return QoSInfo(
        src_qos_profile_latency=src_max_delay,
        src_input_bw=dst_bandwidth,
        src_output_bw=src_bandwidth,
        dst_qos_profile_latency=dst_max_delay,
        dst_input_bw=src_bandwidth,
        dst_output_bw=dst_bandwidth,
    )


def get_custom_config_rule(
    service_config: ServiceConfig, resource_key: str
) -> Optional[ConfigRule]:
    for cr in service_config.config_rules:
        if (
            cr.WhichOneof("config_rule") == "custom"
            and cr.custom.resource_key == resource_key
        ):
            return cr


def get_running_candidate_ietf_slice_data_diff(service_config: ServiceConfig) -> dict:
    running_ietf_slice_cr = get_custom_config_rule(service_config, RUNNING_RESOURCE_KEY)
    running_resource_value_dict = json.loads(
        running_ietf_slice_cr.custom.resource_value
    )
    candidate_ietf_slice_cr = get_custom_config_rule(
        service_config, CANDIDATE_RESOURCE_KEY
    )
    candidate_resource_value_dict = json.loads(
        candidate_ietf_slice_cr.custom.resource_value
    )
    return DeepDiff(
        running_resource_value_dict,
        candidate_resource_value_dict,
    )


def extract_match_criterion_ipv4_info(
    match_criterion: dict,
) -> Ipv4Info:
    for type_value in match_criterion["match-type"]:
        if type_value["type"] == "ietf-network-slice-service:source-ip-prefix":
            src_lan = type_value["value"][0]
        elif type_value["type"] == "ietf-network-slice-service:destination-ip-prefix":
            dst_lan = type_value["value"][0]
        elif type_value["type"] == "ietf-network-slice-service:source-tcp-port":
            src_port = type_value["value"][0]
        elif type_value["type"] == "ietf-network-slice-service:destination-tcp-port":
            dst_port = type_value["value"][0]
        elif type_value["type"] == "ietf-network-slice-service:vlan":
            vlan = type_value["value"][0]
    return Ipv4Info(
        src_lan=src_lan,
        dst_lan=dst_lan,
        src_port=src_port,
        dst_port=dst_port,
        vlan=vlan,
    )


class L3NM_IETFL3VPN_ServiceHandler(_ServiceHandler):
    def __init__(  # pylint: disable=super-init-not-called
        self, service: Service, task_executor: TaskExecutor, **settings
    ) -> None:
        self.__service = service
        self.__task_executor = task_executor
        self.__settings_handler = SettingsHandler(service.service_config, **settings)

    def __find_IP_transport_edge_endpoints(
        self, endpoints
    ) -> Tuple[str, str, str, str, Device]:
        for ep in endpoints:
            device_uuid, endpoint_uuid = get_device_endpoint_uuids(ep)
            device_obj = self.__task_executor.get_device(
                DeviceId(**json_device_id(device_uuid))
            )
            device_controller = self.__task_executor.get_device_controller(device_obj)
            if device_controller.device_type == DeviceTypeEnum.IP_SDN_CONTROLLER.value:
                src_device_uuid, src_endpoint_uuid = device_uuid, endpoint_uuid
                src_device_controller = device_controller
                break
        else:
            raise Exception("No IP transport edge endpoints found")
        for ep in endpoints[::-1]:
            device_uuid, endpoint_uuid = get_device_endpoint_uuids(ep)
            device_obj = self.__task_executor.get_device(
                DeviceId(**json_device_id(device_uuid))
            )
            device_controller = self.__task_executor.get_device_controller(device_obj)
            if device_controller.device_type == DeviceTypeEnum.IP_SDN_CONTROLLER.value:
                dst_device_uuid, dst_endpoint_uuid = device_uuid, endpoint_uuid
                dst_device_controller = device_controller
                break
        else:
            raise Exception("No IP transport edge endpoints found")
        if src_device_controller != dst_device_controller:
            raise Exception("Different Src-Dst devices not supported by now")
        return (
            src_device_uuid,
            src_endpoint_uuid,
            dst_device_uuid,
            dst_endpoint_uuid,
            src_device_controller,
        )

    @metered_subclass_method(METRICS_POOL)
    def SetEndpoint(
        self,
        endpoints: List[Tuple[str, str, Optional[str]]],
        connection_uuid: Optional[str] = None,
    ) -> List[Union[bool, Exception]]:
        chk_type("endpoints", endpoints, list)
        if len(endpoints) < 2:
            return []
        results = []
        service_config = self.__service.service_config
        try:
            (
                src_device_uuid,
                src_endpoint_uuid,
                dst_device_uuid,
                dst_endpoint_uuid,
                controller,
            ) = self.__find_IP_transport_edge_endpoints(endpoints)
            src_device_obj = self.__task_executor.get_device(
                DeviceId(**json_device_id(src_device_uuid))
            )
            src_endpoint_obj = get_endpoint_matching(src_device_obj, src_endpoint_uuid)
            src_device_name = src_device_obj.name
            dst_device_obj = self.__task_executor.get_device(
                DeviceId(**json_device_id(dst_device_uuid))
            )
            dst_endpoint_obj = get_endpoint_matching(dst_device_obj, dst_endpoint_uuid)
            dst_device_name = dst_device_obj.name
            for cr in src_device_obj.device_config.config_rules:
                if (
                    cr.WhichOneof("config_rule") == "custom"
                    and cr.custom.resource_key
                    == f"/endpoints/endpoint[{src_endpoint_obj.name}]"
                ):
                    src_endpoint_settings = json.loads(cr.custom.resource_value)
                    break
            else:
                raise Exception("Endpoint settings not found")
            for cr in dst_device_obj.device_config.config_rules:
                if (
                    cr.WhichOneof("config_rule") == "custom"
                    and cr.custom.resource_key
                    == f"/endpoints/endpoint[{dst_endpoint_obj.name}]"
                ):
                    dst_endpoint_settings = json.loads(cr.custom.resource_value)
                    break
            else:
                raise Exception("Endpoint settings not found")
            ietf_slice_running_cr = get_custom_config_rule(
                service_config, RUNNING_RESOURCE_KEY
            )
            ietf_slice_candidate_cr = get_custom_config_rule(
                service_config, CANDIDATE_RESOURCE_KEY
            )
            if not (
                ietf_slice_running_cr and ietf_slice_candidate_cr
            ):  # The request comes from the IETF Slice NBI
                raise Exception("IETF Slice data not found")
            running_resource_value_dict = json.loads(
                ietf_slice_running_cr.custom.resource_value
            )
            candidate_resource_value_dict = json.loads(
                ietf_slice_candidate_cr.custom.resource_value
            )
            running_candidate_diff = get_running_candidate_ietf_slice_data_diff(
                service_config
            )
            service_id = candidate_resource_value_dict["network-slice-services"][
                "slice-service"
            ][0]["id"]
            if not running_candidate_diff:
                operation_type = "create"
            elif "values_changed" in running_candidate_diff:
                operation_type = "update"
            LOGGER.debug("running_candidate_diff: %s", running_candidate_diff)
            slice_services = candidate_resource_value_dict["network-slice-services"][
                "slice-service"
            ]
            slice_service = slice_services[0]
            sdps = slice_service["sdps"]["sdp"]
            connection_groups = slice_service["connection-groups"]["connection-group"]
            connection_group = connection_groups[0]
            connecitivity_constructs = connection_group["connectivity-construct"]
            connecitivity_construct = connecitivity_constructs[0]
            src_sdp_idx = connecitivity_construct["p2p-sender-sdp"]
            dst_sdp_idx = connecitivity_construct["p2p-receiver-sdp"]
            qos_info = extract_qos_info_from_connection_group(
                src_sdp_idx, dst_sdp_idx, connecitivity_constructs
            )
            src_sdp = next(sdp for sdp in sdps if sdp["id"] == src_sdp_idx)
            dst_sdp = next(sdp for sdp in sdps if sdp["id"] == dst_sdp_idx)
            src_match_criterion = src_sdp["service-match-criteria"]["match-criterion"][
                0
            ]
            dst_match_criterion = dst_sdp["service-match-criteria"]["match-criterion"][
                0
            ]
            src_match_criterion_ipv4_info = extract_match_criterion_ipv4_info(
                src_match_criterion
            )
            dst_match_criterion_ipv4_info = extract_match_criterion_ipv4_info(
                dst_match_criterion
            )
            src_ipv4_lan_prefixes = [
                LANPrefixesDict(
                    lan=src_match_criterion_ipv4_info["dst_lan"],
                    lan_tag=src_match_criterion_ipv4_info["vlan"],
                )
            ]
            dst_ipv4_lan_prefixes = [
                LANPrefixesDict(
                    lan=dst_match_criterion_ipv4_info["dst_lan"],
                    lan_tag=dst_match_criterion_ipv4_info["vlan"],
                )
            ]
            src_ce_address = src_endpoint_settings["address_ip"]
            src_pe_address = src_ce_address
            src_ce_address_prefix = src_endpoint_settings["address_prefix"]
            dst_ce_address = dst_endpoint_settings["address_ip"]
            dst_pe_address = dst_ce_address
            dst_ce_address_prefix = dst_endpoint_settings["address_prefix"]
            resource_value_dict = {
                "uuid": service_id,
                "src_device_name": src_device_name,
                "src_endpoint_name": src_endpoint_obj.name,
                "src_site_location": src_endpoint_settings["site_location"],
                "src_ipv4_lan_prefixes": src_ipv4_lan_prefixes,
                "src_ce_address": src_ce_address,
                "src_pe_address": src_pe_address,
                "src_ce_pe_network_prefix": src_ce_address_prefix,
                "src_mtu": MTU,
                "src_qos_profile_latency": qos_info["src_qos_profile_latency"],
                "src_input_bw": qos_info["src_input_bw"],
                "src_output_bw": qos_info["src_output_bw"],
                "dst_device_name": dst_device_name,
                "dst_endpoint_name": dst_endpoint_obj.name,
                "dst_site_location": dst_endpoint_settings["site_location"],
                "dst_ipv4_lan_prefixes": dst_ipv4_lan_prefixes,
                "dst_ce_address": dst_ce_address,
                "dst_pe_address": dst_pe_address,
                "dst_ce_pe_network_prefix": dst_ce_address_prefix,
                "dst_mtu": MTU,
                "dst_qos_profile_latency": qos_info["dst_qos_profile_latency"],
                "dst_input_bw": qos_info["dst_input_bw"],
                "dst_output_bw": qos_info["dst_output_bw"],
            }
            json_config_rules = setup_config_rules(
                service_id, resource_value_dict, operation_type
            )
            del controller.device_config.config_rules[:]
            for jcr in json_config_rules:
                controller.device_config.config_rules.append(ConfigRule(**jcr))
            self.__task_executor.configure_device(controller)
        except Exception as e:  # pylint: disable=broad-except
            LOGGER.exception(
                "Unable to SetEndpoint for Service({:s})".format(str(service_id))
            )
            results.append(e)

        return results

    @metered_subclass_method(METRICS_POOL)
    def DeleteEndpoint(
        self,
        endpoints: List[Tuple[str, str, Optional[str]]],
        connection_uuid: Optional[str] = None,
    ) -> List[Union[bool, Exception]]:
        chk_type("endpoints", endpoints, list)
        if len(endpoints) < 2:
            return []
        service_config = self.__service.service_config
        ietf_slice_candidate_cr = get_custom_config_rule(
            service_config, CANDIDATE_RESOURCE_KEY
        )
        candidate_resource_value_dict = json.loads(
            ietf_slice_candidate_cr.custom.resource_value
        )
        service_id = candidate_resource_value_dict["network-slice-services"][
            "slice-service"
        ][0]["id"]
        results = []
        try:
            src_device_uuid, _ = get_device_endpoint_uuids(endpoints[0])
            src_device = self.__task_executor.get_device(
                DeviceId(**json_device_id(src_device_uuid))
            )
            src_controller = self.__task_executor.get_device_controller(src_device)

            dst_device_uuid, _ = get_device_endpoint_uuids(endpoints[1])
            dst_device = self.__task_executor.get_device(
                DeviceId(**json_device_id(dst_device_uuid))
            )
            dst_controller = self.__task_executor.get_device_controller(dst_device)
            if (
                src_controller.device_id.device_uuid.uuid
                != dst_controller.device_id.device_uuid.uuid
            ):
                raise Exception("Different Src-Dst devices not supported by now")
            controller = src_controller
            json_config_rules = teardown_config_rules(service_id)
            del controller.device_config.config_rules[:]
            for jcr in json_config_rules:
                controller.device_config.config_rules.append(ConfigRule(**jcr))
            self.__task_executor.configure_device(controller)
            results.append(True)
        except Exception as e:  # pylint: disable=broad-except
            LOGGER.exception(
                "Unable to DeleteEndpoint for Service({:s})".format(str(service_id))
            )
            results.append(e)

        return results

    @metered_subclass_method(METRICS_POOL)
    def SetConstraint(
        self, constraints: List[Tuple[str, Any]]
    ) -> List[Union[bool, Exception]]:
        chk_type("constraints", constraints, list)
        if len(constraints) == 0:
            return []

        msg = "[SetConstraint] Method not implemented. Constraints({:s}) are being ignored."
        LOGGER.warning(msg.format(str(constraints)))
        return [True for _ in range(len(constraints))]

    @metered_subclass_method(METRICS_POOL)
    def DeleteConstraint(
        self, constraints: List[Tuple[str, Any]]
    ) -> List[Union[bool, Exception]]:
        chk_type("constraints", constraints, list)
        if len(constraints) == 0:
            return []

        msg = "[DeleteConstraint] Method not implemented. Constraints({:s}) are being ignored."
        LOGGER.warning(msg.format(str(constraints)))
        return [True for _ in range(len(constraints))]

    @metered_subclass_method(METRICS_POOL)
    def SetConfig(
        self, resources: List[Tuple[str, Any]]
    ) -> List[Union[bool, Exception]]:
        chk_type("resources", resources, list)
        if len(resources) == 0:
            return []

        results = []
        for resource in resources:
            try:
                resource_value = json.loads(resource[1])
                self.__settings_handler.set(resource[0], resource_value)
                results.append(True)
            except Exception as e:  # pylint: disable=broad-except
                LOGGER.exception("Unable to SetConfig({:s})".format(str(resource)))
                results.append(e)

        return results

    @metered_subclass_method(METRICS_POOL)
    def DeleteConfig(
        self, resources: List[Tuple[str, Any]]
    ) -> List[Union[bool, Exception]]:
        chk_type("resources", resources, list)
        if len(resources) == 0:
            return []

        results = []
        for resource in resources:
            try:
                self.__settings_handler.delete(resource[0])
            except Exception as e:  # pylint: disable=broad-except
                LOGGER.exception("Unable to DeleteConfig({:s})".format(str(resource)))
                results.append(e)

        return results
