"""
Silique (https://www.silique.fr)
Copyright (C) 2024-2025

distribued with GPL-2 or later license

This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
"""
import os
from rougail.object_model import CONVERT_OPTION
from rougail.config import RougailConfig
from rougail.error import ExtentionError
from tiramisu.error import ValueOptionError


class RougailUserDataEnvironment:
    def __init__(self,
                 config: 'Config',
                 *,
                 rougailconfig: RougailConfig=None,
                 ):
        # this is the tiramisu config object
        self.config = config
        if rougailconfig is None:
            rougailconfig = RougailConfig
            user_data = rougailconfig['step.user_data']
            if 'environment' not in user_data:
                user_data.append('environment')
                rougailconfig['step.user_data'] = user_data
        user_data = rougailconfig['step.user_data']
        self.rougailconfig = rougailconfig
        if 'environment' not in user_data:
            raise ExtentionError('environment is not set in step.user_data')
        self.errors = []
        self.warnings = []

    def run(self):
        values = self.parse()
        return [{'source': 'environment variable',
                 'errors': self.errors,
                 'warnings': self.warnings,
                 'values': values,
                 'options': {'multi_separator': ',',
                             'needs_convert': True,
                             },
                 }]

    def parse(self):
        variables = {}
        for option in self.config:
            if not option.isoptiondescription() or option.group_type() != "namespace":
                break
            variables.update(get_rougail_environment(option.name()))
        else:
            return variables
        return get_rougail_environment(None, self.rougailconfig['environment.default_environment_name'])


def get_rougail_environment(namespace, environment_name=None):
    """gets all the rougail environment variables and their values

    :sample: {'VARINT': '5', 'VARNAME34': '58, 22', 'VARNAME2': 'tata', 
             'VARNAME1': 'titi', 'MYFAMILY.VARNAME3': 'spam'}
    :returns: rougail environment variables as a key/value dict
    """
    # then we filter the ROUGAIL_ environment variables
    if namespace is None:
        rougail_environment_var = environment_name.upper() + '_'
        len_env = len(rougail_environment_var)
    else:
        rougail_environment_var = namespace.upper() + '.'
        len_env = 0
    return {envvar[len_env:].lower(): envval
            for envvar, envval in os.environ.items()
            if envvar.startswith(rougail_environment_var)}
