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

This program is free software: you can redistribute it and/or modify it
under the terms of the GNU Lesser General Public License as published by the
Free Software Foundation, either version 3 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 Lesser General Public License for more
details.

You should have received a copy of the GNU Lesser General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.
"""

from .config import StaticRougailConvert
from .i18n import _
from .error import DictConsistencyError


class TypeRougailConvert(StaticRougailConvert):
    def __init__(
        self,
        main_structural_directories: list[str],
        secret_pattern: str,
        default_structural_format_version: str,
    ) -> None:
        super().__init__(
            False,
            {
                "sort_structural_files_all": True,
                "main_namespace": None,
                "main_structural_directories": main_structural_directories,
            },
        )
        self.default_structural_format_version = default_structural_format_version
        self.secret_pattern = secret_pattern
        self.loaded_custom_types = {}

    def load_config(self) -> None:
        super().load_config()
        #        self.add_extra_options = self.add_extra_options
        self.sort_structural_files_all = False
        self.structurals = ["directory"]


def rougail_type(rougailconfig):
    types = rougailconfig["types"]
    if not types:
        return {"custom_variable_types": {}, "custom_family_types": {}}
    convert = TypeRougailConvert(
        types,
        rougailconfig["secret_manager.pattern"],
        rougailconfig["default_structural_format_version"],
    )
    convert.init()
    convert.parse_directories()
    loaded_custom_types_keys = list(convert.loaded_custom_types)
    loaded_custom_types_keys.sort()
    for path in loaded_custom_types_keys:
        if "." not in path:
            continue
        current = None
        *spath, name = path.split(".")
        for subpath in spath:
            if not current:
                current = convert.loaded_custom_types[subpath]
            else:
                current = current.children[subpath]
        current.children[name] = convert.loaded_custom_types.pop(path)
    custom_variable_types = {}
    custom_family_types = {}
    for typ, data in convert.loaded_custom_types.items():
        if data.option_type == "variable":
            custom_variable_types[typ] = data
        else:
            custom_family_types[typ] = data
    return {
        "custom_variable_types": custom_variable_types,
        "custom_family_types": custom_family_types,
    }
