#######################################################################################
# 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 traceback

from osm_common.temporal.activities.paas import (
    DeployCharm,
    CheckCharmStatus,
)
from osm_common.temporal.workflows.vdu import VduInstantiateWorkflow
from osm_common.temporal_task_queues.task_queues_mappings import LCM_TASK_QUEUE

from temporalio import workflow
from temporalio.common import RetryPolicy
from temporalio.exceptions import ActivityError

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


@workflow.defn(name=VduInstantiateWorkflow.__name__, sandboxed=False)
class VduInstantiateWorkflowImpl(VduInstantiateWorkflow):
    @workflow.run
    async def run(self, workflow_input: VduInstantiateWorkflow.Input) -> None:
        deploy_charm_input = DeployCharm.Input(
            vim_uuid=workflow_input.vim_uuid,
            model_name=workflow_input.model_name,
            charm_info=workflow_input.charm_info,
            constraints=workflow_input.constraints,
            cloud=workflow_input.cloud,
            config=workflow_input.config,
        )
        try:
            self.logger.info(f"Deploying VDU `{workflow_input.charm_info.app_name}`")
            await workflow.execute_activity(
                activity=DeployCharm.__name__,
                arg=deploy_charm_input,
                activity_id=f"{DeployCharm.__name__}-{workflow_input.vim_uuid}",
                task_queue=LCM_TASK_QUEUE,
                schedule_to_close_timeout=default_schedule_to_close_timeout,
                retry_policy=retry_policy,
            )

            self.logger.info(
                f"Waiting for VDU `{workflow_input.charm_info.app_name}` to become ready"
            )
            await workflow.execute_activity(
                activity=CheckCharmStatus.__name__,
                arg=CheckCharmStatus.Input(
                    vim_uuid=workflow_input.vim_uuid,
                    model_name=workflow_input.model_name,
                    application_name=workflow_input.charm_info.app_name,
                ),
                activity_id=f"{CheckCharmStatus.__name__}-{workflow_input.vim_uuid}",
                task_queue=LCM_TASK_QUEUE,
                start_to_close_timeout=timedelta(minutes=5),
                heartbeat_timeout=timedelta(seconds=30),
                retry_policy=retry_policy,
            )

            self.logger.info(f"VDU `{workflow_input.charm_info.app_name}` is ready")

        except ActivityError as e:
            err_details = str(e.cause.with_traceback(e.__traceback__))
            self.logger.error(
                f"{VduInstantiateWorkflow.__name__} failed with {err_details}"
            )
            raise e

        except Exception as e:
            err_details = str(traceback.format_exc())
            self.logger.error(
                f"{VduInstantiateWorkflow.__name__} failed with {err_details}"
            )
            raise e
