#######################################################################################
# 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.common import RetryPolicy
from temporalio.exceptions import ActivityError

from osm_common.dataclasses.temporal_dataclasses import (
    DeleteVimInput,
    TestVimConnectivityInput,
    UpdateVimOperationStateInput,
    UpdateVimStateInput,
    VimOperationInput,
    VimState,
    VimOperationState,
)
from osm_common.temporal_constants import (
    ACTIVITY_TEST_VIM_CONNECTIVITY,
    ACTIVITY_UPDATE_VIM_OPERATION_STATE,
    ACTIVITY_UPDATE_VIM_STATE,
    ACTIVITY_DELETE_VIM,
    LCM_TASK_QUEUE,
    WORKFLOW_VIM_CREATE,
    WORKFLOW_VIM_UPDATE,
    WORKFLOW_VIM_DELETE,
)

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

workflow.logger = logging.getLogger("lcm.temporal.vim_workflows")


@workflow.defn(name=WORKFLOW_VIM_CREATE, sandboxed=_SANDBOXED)
class VimCreateWorkflow:
    """Updates VIM account state by validating the VIM connectivity."""

    @workflow.run
    async def run(self, input: VimOperationInput) -> None:
        vim_state = UpdateVimStateInput(input.vim_uuid, VimState.ENABLED, "Done")
        op_state = UpdateVimOperationStateInput(
            input.vim_uuid, input.op_id, VimOperationState.COMPLETED, "Done"
        )
        try:
            await workflow.execute_activity(
                activity=ACTIVITY_TEST_VIM_CONNECTIVITY,
                arg=TestVimConnectivityInput(input.vim_uuid),
                activity_id=f"{ACTIVITY_TEST_VIM_CONNECTIVITY}-{input.vim_uuid}",
                task_queue=LCM_TASK_QUEUE,
                schedule_to_close_timeout=default_schedule_to_close_timeout,
                retry_policy=retry_policy,
            )

        except ActivityError as e:
            vim_state = UpdateVimStateInput(
                input.vim_uuid, VimState.ERROR, e.cause.message
            )
            op_state = UpdateVimOperationStateInput(
                input.vim_uuid, input.op_id, VimOperationState.FAILED, e.cause.message
            )

            workflow.logger.error(
                f"{WORKFLOW_VIM_CREATE} failed with {str(e.cause.message)}"
            )
            raise e

        except Exception as e:
            vim_state = UpdateVimStateInput(input.vim_uuid, VimState.ERROR, str(e))
            op_state = UpdateVimOperationStateInput(
                input.vim_uuid, input.op_id, VimOperationState.FAILED, str(e)
            )

            workflow.logger.error(f"{WORKFLOW_VIM_CREATE} failed with {str(e)}")
            raise e

        finally:
            await workflow.execute_activity(
                activity=ACTIVITY_UPDATE_VIM_STATE,
                arg=vim_state,
                activity_id=f"{ACTIVITY_UPDATE_VIM_STATE}-{input.vim_uuid}",
                task_queue=LCM_TASK_QUEUE,
                schedule_to_close_timeout=default_schedule_to_close_timeout,
                retry_policy=retry_policy,
            )

            await workflow.execute_activity(
                activity=ACTIVITY_UPDATE_VIM_OPERATION_STATE,
                arg=op_state,
                activity_id=f"{ACTIVITY_UPDATE_VIM_OPERATION_STATE}-{input.vim_uuid}",
                task_queue=LCM_TASK_QUEUE,
                schedule_to_close_timeout=default_schedule_to_close_timeout,
                retry_policy=retry_policy,
            )


@workflow.defn(name=WORKFLOW_VIM_UPDATE, sandboxed=_SANDBOXED)
class VimUpdateWorkflow(VimCreateWorkflow):
    """Updates VIM account state by validating the VIM connectivity."""

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


@workflow.defn(name=WORKFLOW_VIM_DELETE, sandboxed=_SANDBOXED)
class VimDeleteWorkflow:
    """Deletes VIM accounts."""

    @workflow.run
    async def run(self, input: VimOperationInput) -> None:
        await workflow.execute_activity(
            activity=ACTIVITY_DELETE_VIM,
            arg=DeleteVimInput(input.vim_uuid),
            activity_id=f"{ACTIVITY_UPDATE_VIM_STATE}-{input.vim_uuid}",
            task_queue=LCM_TASK_QUEUE,
            schedule_to_close_timeout=default_schedule_to_close_timeout,
            retry_policy=retry_policy,
        )
