#  Copyright 2023 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#  SPDX-License-Identifier: Apache-2.0
import json

import jmespath
import luigi

from servicecatalog_puppet import constants
from servicecatalog_puppet.workflow.dependencies import tasks


class GetS3ParameterTask(tasks.TaskWithReference):
    account_id = luigi.Parameter()
    s3_object_task_reference = luigi.Parameter()
    key = luigi.Parameter()
    jmespath_location = luigi.Parameter()
    default = luigi.Parameter()
    region = luigi.Parameter()
    cachable_level = constants.CACHE_LEVEL_RUN

    def params_for_results_display(self):
        return {
            "task_reference": self.task_reference,
            "account_id": self.account_id,
            "region": self.region,
            "key": self.key,
            "jmespath_location": self.jmespath_location,
        }

    def run(self):
        object = self.get_output_from_reference_dependency(
            self.s3_object_task_reference
        )
        result = jmespath.search(self.jmespath_location, object)
        if result is None:
            if self.default is None:
                raise Exception(
                    "Could not find value in the s3 JSON object and there is no default value."
                    "Check your JMESPath is correct."
                )
            else:
                result = self.default
        self.write_output(result)
