#######################################################################################
# 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 temporalio import workflow
from temporalio.converter import value_to_type
from temporalio.exceptions import ActivityError

from osm_common.dataclasses.temporal_dataclasses import (
    ModelInfo,
    NsInstantiateInput,
    NsLcmOperationInput,
    NsState,
    UpdateNsStateInput,
)
from osm_common.temporal_constants import (
    ACTIVITY_CREATE_MODEL,
    ACTIVITY_CHECK_NS_INSTANTIATION_FINISHED,
    ACTIVITY_DEPLOY_NS,
    ACTIVITY_GET_MODEL_INFO,
    ACTIVITY_UPDATE_NS_STATE,
    LCM_TASK_QUEUE,
    WORKFLOW_NS_INSTANTIATE,
)

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:
        # Temporary until we align on what is really needed where.  For now, this
        # reduced set looks to be all that is needed.
        input = NsInstantiateInput(
            ns_uuid=input.nslcmop["nsInstanceId"], op_id=input.nslcmop["_id"]
        )

        ns_state = UpdateNsStateInput(input.ns_uuid, NsState.INSTANTIATED, "Done")
        try:
            model_info = value_to_type(
                ModelInfo,
                await workflow.execute_activity(
                    activity=ACTIVITY_GET_MODEL_INFO,
                    arg=input,
                    activity_id=f"{ACTIVITY_GET_MODEL_INFO}-{input.ns_uuid}",
                    task_queue=LCM_TASK_QUEUE,
                    schedule_to_close_timeout=LcmOperationWorkflow.default_schedule_to_close_timeout,
                    retry_policy=LcmOperationWorkflow.no_retry_policy,
                ),
            )

            await workflow.execute_activity(
                activity=ACTIVITY_CREATE_MODEL,
                arg=model_info,
                activity_id=f"{ACTIVITY_CREATE_MODEL}-{input.ns_uuid}",
                task_queue=LCM_TASK_QUEUE,
                schedule_to_close_timeout=LcmOperationWorkflow.default_schedule_to_close_timeout,
                retry_policy=LcmOperationWorkflow.no_retry_policy,
            )

            # TODO: Change this to a workflow OSM-990
            await workflow.execute_activity(
                activity=ACTIVITY_DEPLOY_NS,
                arg=input,
                activity_id=f"{ACTIVITY_DEPLOY_NS}-{input.ns_uuid}",
                task_queue=LCM_TASK_QUEUE,
                schedule_to_close_timeout=LcmOperationWorkflow.default_schedule_to_close_timeout,
                retry_policy=LcmOperationWorkflow.no_retry_policy,
            )

            await workflow.execute_activity(
                activity=ACTIVITY_CHECK_NS_INSTANTIATION_FINISHED,
                arg=input,
                activity_id=f"{ACTIVITY_CHECK_NS_INSTANTIATION_FINISHED}-{input.ns_uuid}",
                task_queue=LCM_TASK_QUEUE,
                schedule_to_close_timeout=LcmOperationWorkflow.default_schedule_to_close_timeout,
                retry_policy=LcmOperationWorkflow.retry_policy,
            )

        except ActivityError as e:
            ns_state = UpdateNsStateInput(input.ns_uuid, NsState.ERROR, e.cause.message)
            self.logger.error(
                f"{WORKFLOW_NS_INSTANTIATE} failed with {str(e.cause.message)}"
            )
            raise e

        except Exception as e:
            ns_state = UpdateNsStateInput(input.ns_uuid, NsState.ERROR, str(e))
            self.logger.error(f"{WORKFLOW_NS_INSTANTIATE} failed with {str(e)}")
            raise e

        finally:
            await workflow.execute_activity(
                activity=ACTIVITY_UPDATE_NS_STATE,
                arg=ns_state,
                activity_id=f"{ACTIVITY_UPDATE_NS_STATE}-{input.ns_uuid}",
                task_queue=LCM_TASK_QUEUE,
                schedule_to_close_timeout=LcmOperationWorkflow.default_schedule_to_close_timeout,
                retry_policy=LcmOperationWorkflow.retry_policy,
            )
