#######################################################################################
# Copyright ETSI Contributors and Others.
#
# 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.

from datetime import timedelta
import logging
from temporalio import workflow
from temporalio.converter import value_to_type
from temporalio.common import RetryPolicy

from osm_common.dataclasses.temporal_dataclasses import (
    VnfInstantiationState,
    VnfState,
    VnfInstantiateInput,
    VduInstantiateInput,
    ChangeVnfInstantiationStateInput,
    ChangeVnfStateInput,
    GetTaskQueueInput,
    GetTaskQueueOutput,
    GetVnfDetailsInput,
    GetVnfDetailsOutput,
)

from osm_common.temporal_constants import (
    ACTIVITY_CHANGE_VNF_INSTANTIATION_STATE,
    ACTIVITY_SEND_NOTIFICATION_FOR_VNF,
    ACTIVITY_CHANGE_VNF_STATE,
    ACTIVITY_GET_TASK_QUEUE,
    ACTIVITY_GET_VNF_DETAILS,
    ACTIVITY_SET_VNF_MODEL,
    LCM_TASK_QUEUE,
    WORKFLOW_VDU_INSTANTIATE,
    WORKFLOW_VNF_INSTANTIATE,
    WORKFLOW_VNF_PREPARE,
)
from osm_lcm.temporal.juju_paas_activities import CharmInfoUtils

_SANDBOXED = False
retry_policy = RetryPolicy(maximum_attempts=3)
default_schedule_to_close_timeout = timedelta(minutes=10)


@workflow.defn(name=WORKFLOW_VNF_INSTANTIATE, sandboxed=_SANDBOXED)
class VnfInstantiateWorkflow:
    """Instantiate a VNF.

    Workflow Identifier:
        It is recommended that the ID for the VNF is referred as a workflow
        ID when invoking this workflow.
    """

    def __init__(self):
        self.logger = logging.getLogger(f"lcm.wfl.{self.__class__.__name__}")

    @workflow.run
    async def run(self, input: VnfInstantiateInput) -> None:
        self.logger.info(f"Deploying VNF {input.vnfr_uuid}")
        vnf_instantiation_state = ChangeVnfInstantiationStateInput(
            vnfr_uuid=input.vnfr_uuid, state=VnfInstantiationState.NOT_INSTANTIATED
        )
        vnf_state = ChangeVnfStateInput(
            vnfr_uuid=input.vnfr_uuid, state=VnfState.STOPPED
        )
        try:
            await self.update_states(
                vnf_instantiation_state=vnf_instantiation_state,
                vnf_state=vnf_state,
            )
            vnf_task_queue = value_to_type(
                GetTaskQueueOutput,
                await workflow.execute_activity(
                    activity=ACTIVITY_GET_TASK_QUEUE,
                    arg=GetTaskQueueInput(input.vnfr_uuid),
                    activity_id=f"{ACTIVITY_GET_TASK_QUEUE}-{input.vnfr_uuid}",
                    task_queue=LCM_TASK_QUEUE,
                    schedule_to_close_timeout=default_schedule_to_close_timeout,
                    retry_policy=retry_policy,
                ),
            )

            self.logger.debug(f"Dependent task queue is {vnf_task_queue.task_queue}")

            await workflow.execute_child_workflow(
                workflow=WORKFLOW_VNF_PREPARE,
                arg=input,
                task_queue=vnf_task_queue.task_queue,
                id=f"{WORKFLOW_VNF_PREPARE}-{input.vnfr_uuid}",
            )

            get_vnf_details = value_to_type(
                GetVnfDetailsOutput,
                await workflow.execute_activity(
                    activity=ACTIVITY_GET_VNF_DETAILS,
                    arg=GetVnfDetailsInput(input.vnfr_uuid),
                    activity_id=f"{ACTIVITY_GET_VNF_DETAILS}-{input.vnfr_uuid}",
                    task_queue=vnf_task_queue.task_queue,
                    schedule_to_close_timeout=default_schedule_to_close_timeout,
                    retry_policy=retry_policy,
                ),
            )

            await self.instantiate_vdus(
                get_vnf_details.vnfr, get_vnf_details.vnfd, vnf_task_queue.task_queue
            )
            await self.update_states(
                vnf_instantiation_state=ChangeVnfInstantiationStateInput(
                    vnfr_uuid=input.vnfr_uuid, state=VnfInstantiationState.INSTANTIATED
                ),
                vnf_state=ChangeVnfStateInput(
                    vnfr_uuid=input.vnfr_uuid, state=VnfState.STARTED
                ),
            )

        except Exception as e:
            workflow.logger.error(f"{WORKFLOW_VNF_INSTANTIATE} failed with {str(e)}")
            await self.update_states(
                vnf_instantiation_state=vnf_instantiation_state,
                vnf_state=vnf_state,
            )
            raise e

    @staticmethod
    async def update_vnf_state(vnf_state):
        await workflow.execute_activity(
            activity=ACTIVITY_CHANGE_VNF_STATE,
            arg=vnf_state,
            activity_id=f"{ACTIVITY_CHANGE_VNF_STATE}-{vnf_state.vnfr_uuid}",
            task_queue=LCM_TASK_QUEUE,
            schedule_to_close_timeout=default_schedule_to_close_timeout,
            retry_policy=retry_policy,
        )

    @staticmethod
    async def update_vnf_instantiation_state(vnf_instantiation_state):
        await workflow.execute_activity(
            activity=ACTIVITY_CHANGE_VNF_INSTANTIATION_STATE,
            arg=vnf_instantiation_state,
            activity_id=f"{ACTIVITY_CHANGE_VNF_INSTANTIATION_STATE}-{vnf_instantiation_state.vnfr_uuid}",
            task_queue=LCM_TASK_QUEUE,
            schedule_to_close_timeout=default_schedule_to_close_timeout,
            retry_policy=retry_policy,
        )

    @staticmethod
    async def send_notification_for_vnf(
        vnf_instantiation_state: ChangeVnfInstantiationStateInput,
    ):
        await workflow.execute_activity(
            activity=ACTIVITY_SEND_NOTIFICATION_FOR_VNF,
            arg=vnf_instantiation_state,
            activity_id=f"{ACTIVITY_SEND_NOTIFICATION_FOR_VNF}-{vnf_instantiation_state.vnfr_uuid}",
            task_queue=LCM_TASK_QUEUE,
            schedule_to_close_timeout=default_schedule_to_close_timeout,
            retry_policy=retry_policy,
        )

    @staticmethod
    async def instantiate_vdus(vnfr: dict, vnfd: dict, task_queue: str):
        for vdu in vnfd.get("vdu"):
            (
                vdu_instantiate_input,
                vdu_instantiate_workflow_id,
            ) = VnfInstantiateWorkflow.get_vdu_instantiate_input(vnfr, vnfd, vdu)
            await workflow.execute_child_workflow(
                workflow=WORKFLOW_VDU_INSTANTIATE,
                arg=vdu_instantiate_input,
                task_queue=task_queue,
                id=vdu_instantiate_workflow_id,
            )

    @staticmethod
    def get_vdu_instantiate_input(vnfr: dict, vnfd: dict, vdu: dict):
        model_name = vnfr.get("namespace")
        vim_id = vnfr.get("vim-account-id")
        sw_image_descs = vnfd.get("sw-image-desc")
        vdu_info = CharmInfoUtils.get_charm_info(vdu, sw_image_descs)
        vdu_instantiate_input = VduInstantiateInput(vim_id, model_name, vdu_info)
        vdu_instantiate_workflow_id = (
            vdu_instantiate_input.model_name
            + "-"
            + vdu_instantiate_input.charm_info.app_name
        )
        return vdu_instantiate_input, vdu_instantiate_workflow_id

    async def update_states(
        self,
        vnf_instantiation_state: ChangeVnfInstantiationStateInput,
        vnf_state: ChangeVnfStateInput,
    ):
        await self.update_vnf_instantiation_state(vnf_instantiation_state)
        await self.update_vnf_state(vnf_state)
        await self.send_notification_for_vnf(vnf_instantiation_state)


@workflow.defn(name=WORKFLOW_VNF_PREPARE, sandboxed=_SANDBOXED)
class VnfPrepareWorkflow:
    """Prepare a VNF.

    Workflow Identifier:
        It is recommended that the ID for the VNF is referred as a workflow
        ID when invoking this workflow.
    """

    def __init__(self):
        self.logger = logging.getLogger(f"lcm.wfl.{self.__class__.__name__}")

    @workflow.run
    async def run(self, wf_input: VnfInstantiateInput) -> None:
        try:
            await workflow.execute_activity(
                activity=ACTIVITY_SET_VNF_MODEL,
                arg=wf_input,
                activity_id=f"{ACTIVITY_SET_VNF_MODEL}-{wf_input.vnfr_uuid}",
                task_queue=LCM_TASK_QUEUE,
                schedule_to_close_timeout=default_schedule_to_close_timeout,
                retry_policy=retry_policy,
            )
        except Exception as e:
            self.logger.error(f"{WORKFLOW_VNF_PREPARE} failed with {str(e)}")
            raise e
