#######################################################################################
# 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 osm_common.dataclasses.temporal_dataclasses import (
    GetVnfRecordIdsInput,
    GetVnfRecordIdsOutput,
    ModelInfo,
    NsLcmOperationInput,
    NsState,
    UpdateNsStateInput,
    VnfInstantiateInput,
)
from osm_common.temporal_constants import (
    ACTIVITY_CREATE_MODEL,
    ACTIVITY_GET_VNF_RECORD_IDS,
    ACTIVITY_UPDATE_NS_STATE,
    WORKFLOW_NS_INSTANTIATE,
    WORKFLOW_VNF_INSTANTIATE,
)
from temporalio import workflow
from temporalio.converter import value_to_type
from temporalio.exceptions import ActivityError

from osm_lcm.temporal.lcm_workflows import LcmOperationWorkflow


@workflow.defn(name=WORKFLOW_NS_INSTANTIATE, sandboxed=LcmOperationWorkflow._SANDBOXED)
class NsInstantiateWorkflow(LcmOperationWorkflow):
    """Instantiate a NS"""

    @workflow.run
    async def wrap_nslcmop(self, input: NsLcmOperationInput) -> None:
        await super().wrap_nslcmop(input=input)

    async def workflow(self, input: NsLcmOperationInput) -> None:
        self.logger.info(f"Executing {WORKFLOW_NS_INSTANTIATE} with {input}")

        # TODO: Can we clean up the input? Perhaps this workflow could receive NsInstantiateInput
        # directly.
        ns_uuid = input.nslcmop["nsInstanceId"]
        vim_uuid = input.nslcmop["operationParams"]["vimAccountId"]
        model_name = self._get_namespace(ns_uuid, vim_uuid)
        try:
            await workflow.execute_activity(
                activity=ACTIVITY_CREATE_MODEL,
                arg=ModelInfo(vim_uuid=vim_uuid, model_name=model_name),
                activity_id=f"{ACTIVITY_CREATE_MODEL}-{ns_uuid}",
                schedule_to_close_timeout=LcmOperationWorkflow.default_schedule_to_close_timeout,
                retry_policy=LcmOperationWorkflow.no_retry_policy,
            )

            vnf_record_ids_output: GetVnfRecordIdsOutput = value_to_type(
                GetVnfRecordIdsOutput,
                await workflow.execute_activity(
                    activity=ACTIVITY_GET_VNF_RECORD_IDS,
                    arg=GetVnfRecordIdsInput(ns_uuid=ns_uuid),
                    activity_id=f"{ACTIVITY_GET_VNF_RECORD_IDS}-{ns_uuid}",
                    schedule_to_close_timeout=LcmOperationWorkflow.default_schedule_to_close_timeout,
                    retry_policy=LcmOperationWorkflow.no_retry_policy,
                ),
            )

            for vnfr_uuid in vnf_record_ids_output.vnfr_ids:
                await workflow.execute_child_workflow(
                    workflow=WORKFLOW_VNF_INSTANTIATE,
                    arg=VnfInstantiateInput(vnfr_uuid=vnfr_uuid, model_name=model_name),
                    id=f"{WORKFLOW_VNF_INSTANTIATE}-{vnfr_uuid}",
                )

        except ActivityError as e:
            await self.update_ns_state(ns_uuid, NsState.INSTANTIATED, e.cause.message)
            self.logger.error(
                f"{WORKFLOW_NS_INSTANTIATE} failed with {str(e.cause.message)}"
            )
            raise e

        except Exception as e:
            await self.update_ns_state(ns_uuid, NsState.INSTANTIATED, str(e))
            self.logger.error(f"{WORKFLOW_NS_INSTANTIATE} failed with {str(e)}")
            raise e
        await self.update_ns_state(ns_uuid, NsState.INSTANTIATED, "Done")

    @staticmethod
    async def update_ns_state(
        ns_uuid: str,
        state: NsState,
        message: str,
    ) -> None:
        input = UpdateNsStateInput(ns_uuid, state, message)
        await workflow.execute_activity(
            activity=ACTIVITY_UPDATE_NS_STATE,
            arg=input,
            activity_id=f"{ACTIVITY_UPDATE_NS_STATE}-{ns_uuid}",
            schedule_to_close_timeout=LcmOperationWorkflow.default_schedule_to_close_timeout,
            retry_policy=LcmOperationWorkflow.retry_policy,
        )

    def _get_namespace(self, ns_id: str, vim_id: str) -> str:
        """The NS namespace is the combination if the NS ID and the VIM ID."""
        return ns_id[-12:] + "-" + vim_id[-12:]
