"""
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 _


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

    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 {}, {}
    convert = TypeRougailConvert(types)
    convert.init()
    convert.parse_directories()
    return ({typ: to_dict_variable(convert.paths[typ]) for typ in convert.variables},
            {typ: to_dict_family(typ, convert.paths, convert.parents, convert.families) for typ in convert.families},
            )


def to_dict_variable(obj, with_files=True):
    if with_files:
        keys = ['name', 'path']
    else:
        keys = ['name', 'path', 'xmlfiles']
    return {key: value for key, value in dict(obj).items() if key not in keys and value is not None}


def to_dict_family(family_name, paths, parents, families, root=True):
    ret = to_dict_variable(paths[family_name], root)
    for variable_path in parents[family_name]:
        variable = paths[variable_path]
        variable_name = variable.name
        if variable_path in families:
            if variable.type == "leadership":
                raise DictConsistencyError(_("type is not compatible with leadership family"), variable.xmlfiles)
            if variable.type == "dynamic":
                raise DictConsistencyError(_("type is not compatible with dynamic family"), variable.xmlfiles)
            if variable_name in ret:
                ret["_" + variable_name] = ret.pop(variable_name)
            ret[variable_name] = to_dict_family(variable.path, paths, parents, families, False)
        else:
            ret[variable_name] = to_dict_variable(variable, False)
    return ret
