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


import asyncio
from time import time


async def check_workflow_status(self, workflow_name):
    self.logger.info(f"Async check workflow status Enter: {workflow_name}")
    start_time = time()
    timeout = 300
    retry_time = 15
    # TODO: Maybe it's better not to measure time, but controlling retries
    # retries = 0
    # total_retries = int(timeout/retry_time)
    while time() <= start_time + timeout:
        # workflow_list = await self._kubectl.list_generic_object(
        #         api_group="argoproj.io",
        #         api_plural="workflows",
        #         api_version="v1alpha1",
        #         namespace="osm-workflows",
        # )
        # self.logger.info(f"Workflow_list: { workflow_list }")
        # kubectl get workflow/${WORKFLOW_NAME} -n osm-workflows -o jsonpath='{.status.conditions}' | jq -r '.[] | select(.type=="Completed").status'
        workflow = await self._kubectl.get_generic_object(
            api_group="argoproj.io",
            api_plural="workflows",
            api_version="v1alpha1",
            namespace="osm-workflows",
            name=workflow_name,
        )
        # self.logger.info(f"Workflow: {workflow}")
        # self.logger.info(f"Workflow status: {workflow.get('status')}")
        conditions = workflow.get("status", {}).get("conditions", [])
        self.logger.info(f"Workflow status conditions: {conditions}")
        result = next((item for item in conditions if item["type"] == "Completed"), {})
        if result.get("status", "False") == "True":
            self.logger.info(
                f"Workflow {workflow_name} completed in {time() - start_time} seconds"
            )
            return True, "COMPLETED"
        await asyncio.sleep(retry_time)
    return False, "Workflow {workflow_name} did not complete in {timeout} seconds"
