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

from osm_common.dataclasses.temporal_dataclasses import (
    VduInstantiateInput,
    CheckCharmStatusInput,
)

from osm_common.temporal_constants import (
    ACTIVITY_DEPLOY_CHARM,
    ACTIVITY_CHECK_CHARM_STATUS,
    LCM_TASK_QUEUE,
    WORKFLOW_VDU_INSTANTIATE,
)

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


@workflow.defn(name=WORKFLOW_VDU_INSTANTIATE, sandboxed=_SANDBOXED)
class VduInstantiateWorkflow:
    """Instantiate a VDU"""

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

    @workflow.run
    async def run(self, input: VduInstantiateInput) -> None:
        try:
            self.logger.info(f"Deploying VDU `{input.charm_info.app_name}`")
            await workflow.execute_activity(
                activity=ACTIVITY_DEPLOY_CHARM,
                arg=input,
                activity_id=f"{ACTIVITY_DEPLOY_CHARM}-{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 `{input.charm_info.app_name}` to become ready"
            )
            await workflow.execute_activity(
                activity=ACTIVITY_CHECK_CHARM_STATUS,
                arg=CheckCharmStatusInput(
                    vim_uuid=input.vim_uuid,
                    model_name=input.model_name,
                    application_name=input.charm_info.app_name,
                ),
                activity_id=f"{ACTIVITY_CHECK_CHARM_STATUS}-{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 `{input.charm_info.app_name}` is ready")

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

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