"""
Silique (https://www.silique.fr)
Copyright (C) 2024-2025
            
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 typing import Optional
from ruamel.yaml import CommentedMap

from .utils import _, calc_path


class Examples:  # pylint: disable=no-member,too-few-public-methods
    """Build examples"""

    def __init__(self):
        self.examples = None
        self.examples_mandatories = None

    def gen_doc_examples(self):
        """Return examples"""
        root = self.rougailconfig["doc.root"]
        self.comment_examples = self.rougailconfig["doc.comment_examples"]
        self.level = self.rougailconfig["doc.title_level"]
        if self.comment_examples:
            self.comment_examples_column = self.rougailconfig["doc.comment_examples_column"]
        self._build_examples(root)
        return_string = ""
        datas = []
        if self.examples_mandatories:
            datas.extend([
                self.formatter.title(
                    _("Example with mandatory variables not filled in"), self.level
                ),
                self.formatter.yaml(self.examples_mandatories),
                self.formatter.end_family(self.level),
                ])
        if self.examples:
            datas.extend([self.formatter.title(
                            _("Example with all variables modifiable"), self.level
                          ),
                          self.formatter.yaml(self.examples),
                          self.formatter.end_family(self.level),
                          ])
        return self.formatter.compute(datas)

    def _build_examples(self, root):
        examples, examples_mandatories = self._parse_examples(
            self.informations
        )
        if root and examples:
            sub_examples = examples
            sub_examples_mandatories = examples_mandatories
            new_examples_mandatories = examples_mandatories = {}
            new_examples = examples = {}
            for sub in root.split('.'):
                new_examples[sub] = {}
                new_examples = new_examples[sub]
                sub_examples = sub_examples[sub]
                if examples_mandatories and sub in sub_examples_mandatories:
                    new_examples_mandatories[sub] = {}
                    new_examples_mandatories = new_examples_mandatories[sub]
                    sub_examples_mandatories = sub_examples_mandatories[sub]
                else:
                    new_examples_mandatories = {}
                    sub_examples_mandatories = {}
            new_examples.update(sub_examples)
            new_examples_mandatories.update(sub_examples_mandatories)
        self.examples = examples
        self.examples_mandatories = examples_mandatories

    def _parse_examples(self, dico, dyn_parent: Optional[str] = None) -> tuple:
        if self.comment_examples:
            examples = CommentedMap()
            examples_mandatories = CommentedMap()
        else:
            examples = {}
            examples_mandatories = {}
        for value in dico.values():
            if value["type"] == "variable":
                parse = self._parse_examples_variable
            else:
                parse = self._parse_examples_family
            parse(
                value, dyn_parent, examples, examples_mandatories
            )
        return examples, examples_mandatories

    def _parse_examples_variable(
        self,
        variable,
        dyn_parent: Optional[str],
        examples: dict,
        examples_mandatories: dict,
    ) -> None:
        paths = []
        ori_path = variable["path"]
        if "identifiers" in variable:
            for idx, identifiers in enumerate(variable["identifiers"]):
                paths.append(calc_path(ori_path, identifiers=identifiers))
        else:
            paths.append(ori_path)
        for idx, path in enumerate(paths):
            path = calc_path(path)
            if dyn_parent is not None and not path.startswith(dyn_parent):
                continue
            if len(variable["names"]) == 1:
                name = variable["names"][0]
            else:
                name = variable["names"][idx]
            value = variable["gen_examples"][idx]
            examples[name] = value
            if self.comment_examples and "description" in variable:
                description = variable["description"]
                if description.endswith('.'):
                    description = description[:-1]
                examples.yaml_add_eol_comment(description, name, column=self.comment_examples_column)
            if variable["mandatory_without_value"]:
                examples_mandatories[name] = value
                if self.comment_examples and "description" in variable:
                    description = variable["description"]
                    if description.endswith('.'):
                        description = description[:-1]
                    examples_mandatories.yaml_add_eol_comment(description, name, column=self.comment_examples_column)
            break

    def _parse_examples_family(
        self,
        family,
        dyn_parent: Optional[str],
        examples: dict,
        examples_mandatories: dict,
    ) -> None:
        def _set_example(idx, identifiers):
            path = calc_path(ori_path, identifiers=identifiers)
            if dyn_parent is not None and not path.startswith(dyn_parent):
                return
            if len(family["informations"]["names"]) == 1:
                name = family["informations"]["names"][0]
            else:
                name = family["informations"]["names"][idx]
            if family["type"] == "leadership":
                func = self._parse_examples_leadership
            else:
                func = self._parse_examples
            ret_e, ret_m = func(
                family["children"],
                path + "." if family["type"] == "dynamic" else dyn_parent,
            )
            if ret_m:
                examples_mandatories[name] = ret_m
                if self.comment_examples and "description" in family["informations"]:
                    description = family["informations"]["description"]
                    if description.endswith('.'):
                        description = description[:-1]
                    examples_mandatories.yaml_add_eol_comment(description, name, column=self.comment_examples_column)
            if ret_e:
                examples[name] = ret_e
                if self.comment_examples and "description" in family["informations"]:
                    description = family["informations"]["description"]
                    if description.endswith('.'):
                        description = description[:-1]
                    examples.yaml_add_eol_comment(description, name, column=self.comment_examples_column)

        ori_path = family["informations"]["path"]
        if "identifiers" in family["informations"]:
            for idx, identifiers in enumerate(family["informations"]["identifiers"]):
                _set_example(idx, identifiers)
        else:
            _set_example(0, None)

    def _parse_examples_leadership(
        self, leadership, dyn_parent: Optional[str] = None
    ) -> tuple:
        examples = []
        examples_mandatories = []
        leader = next(iter(leadership.values()))
        paths = []
        ori_path = leader["path"]
        if "identifiers" in leader:
            for idx, identifiers in enumerate(leader["identifiers"]):
                paths.append(calc_path(ori_path, identifiers=identifiers))
        else:
            paths.append(ori_path)
        for path_idx, path in enumerate(paths):
            path = calc_path(path)
            if dyn_parent is not None and not path.startswith(dyn_parent):
                continue
            for leader_idx in range(len(leader["gen_examples"][path_idx])):
                if self.comment_examples:
                    followers = CommentedMap()
                else:
                    followers = {}
                for follower in leadership.values():
                    if len(follower["names"]) == 1:
                        name = follower["names"][0]
                    else:
                        name = follower["names"][path_idx]
                    followers[name] = follower["gen_examples"][path_idx][leader_idx]
                    if self.comment_examples and "description" in follower:
                        description = follower["description"]
                        if description.endswith('.'):
                            description = description[:-1]
                        followers.yaml_add_eol_comment(description, name, column=self.comment_examples_column)
                examples.append(followers)
                if leader["mandatory_without_value"]:
                    if self.comment_examples:
                        followers = CommentedMap()
                    else:
                        followers = {}
                    for follower in leadership.values():
                        if not follower["mandatory_without_value"]:
                            continue
                        if len(follower["names"]) == 1:
                            name = follower["names"][0]
                        else:
                            name = follower["names"][path_idx]
                        followers[name] = follower["gen_examples"][path_idx][leader_idx]
                        if self.comment_examples and "description" in follower:
                            description = follower["description"]
                            if description.endswith('.'):
                                description = description[:-1]
                            followers.yaml_add_eol_comment(description, name, column=self.comment_examples_column)
                    examples_mandatories.append(followers)
            break
        return examples, examples_mandatories
