"""Step Implementer for the 'validate-environment-config' step for ConfiglintFromArgocd.

The ConfiglintFromArogcd step takes the output of the Deploy (argocd) step and prepares
it as input for the Configlint step.

Step Configuration
------------------

Step configuration key(s) for this step:

| Key               | Required | Default                   | Description
|-------------------|----------|---------------------------|-----------
|                   |          |                           |

.. Note:: No required keys


Expected Previous Step Results
------------------------------

Results expected from previous steps:

| Step Name           |  Key                | Description
|---------------------|---------------------|------------
| `deploy`            | `report-artifacts`  | name='argocd-result-set'
|                     |                     | path='file:///folder/file.yml'

Results
-------

Results output by this step:

| Key                              | Description
|----------------------------------|------------
| `result`                         | A dictionary describing the output \
                                     of this step
| `report-artifacts`               | An array of dictionaries describing \
                                     artifacts generated by this step

Elements in `result` dictionary:

| Key          | Description
|--------------|------------
| `success`    | Boolean value describing success/failure of this step
| `message`    | Human readable message describing results of this step

Elements in `report-artifacts` dictionary:

|  Key         | Description
|--------------|------------
| `name`       | Human readable name for report artifact generated by this step
| `path`       | Absolute path (including transport protocol) to the step report artifact


Examples
--------

**Example: Step Configuration (minimal)**

    validate-environment-configuration:
    - implementer: ConfiglintFromArgocd

**Example: Previous Results**

    'tssc-results': {
        'deploy': {
            'report-artifacts': {
                'argocd-result-set': 'file:///home/user/tssc-work/deploy/file.yml'
            }
    }

**Example: Results**

    'tssc-results': {
        'validate-environment-configuration': {
            'options': {
                'yml_path': '/folder/file.yml'
            }
    }

"""

import os
from urllib.parse import urlparse

from tssc import StepImplementer

DEFAULT_CONFIG = {
}

REQUIRED_CONFIG_KEYS = {
}

AUTHENTICATION_CONFIG = {
}

class ConfiglintFromArgocd(StepImplementer):
    """
    StepImplementer for the tag-source step for Config_lint.
    """

    @staticmethod
    def step_implementer_config_defaults():
        """
        Getter for the StepImplementer's configuration defaults.

        Notes
        -----
        These are the lowest precedence configuration values.

        Returns
        -------
        dict
            Default values to use for step configuration values.
        """
        return DEFAULT_CONFIG

    @staticmethod
    def required_runtime_step_config_keys():
        """
        Getter for step configuration keys that are required before running the step.

        See Also
        --------
        _validate_runtime_step_config

        Returns
        -------
        array_list
            Array of configuration keys that are required before running the step.
        """
        return REQUIRED_CONFIG_KEYS

    def _run_step(self):
        """
        Runs the TSSC step implemented by this StepImplementer.

        Parameters
        ----------
        runtime_step_config : dict
            Step configuration to use when the StepImplementer runs the step with all of the
            various static, runtime, defaults, and environment configuration munged together.

        Returns
        -------
        dict
            Results of running this step.
        """

        yml_path = ''
        if (self.get_step_results('deploy') and
                self.get_step_results('deploy').get('report-artifacts')):
            artifacts = self.get_step_results('deploy').get('report-artifacts')
            for artifact in artifacts:
                name = artifact['name']
                if name == 'argocd-result-set':
                    yml_path = artifact['path']
        else:
            raise ValueError('Deploy results is missing report-artifacts')
        if yml_path == '':
            raise ValueError('Deploy results missing yml element name=argocd-result-set')

        # The expected format:  file:///folder/file.yml
        yml_path = urlparse(yml_path).path
        if not os.path.exists(yml_path):
            raise ValueError(f'File not found {yml_path}')

        results = {
            'result': {
                'success': True,
                'message': 'configlint prep step completed',
            },
            'options': {
                'yml_path': yml_path
            }
        }
        return results
