"""Generated param reconstruction for {{ directive_name }}."""
from __future__ import annotations

from typing import Any, Dict, Tuple


_OPTION_MAP = {
{% for m in option_mappings %}
    '{{ m.option_name }}': (({% for seg in m.param_path %}'{{ seg }}'{% if not loop.last %}, {% endif %}{% endfor %}{% if m.param_path | length == 1 %},{% endif %}), {{ m.is_negated }}),
{% endfor %}
}
{% if body_mapping %}

_BODY_PATH = ({% for seg in body_mapping.param_path %}'{{ seg }}'{% if not loop.last %}, {% endif %}{% endfor %}{% if body_mapping.param_path | length == 1 %},{% endif %})
{% endif %}


def _set_nested(d, path, value):
    """Set a value in a nested dict, creating intermediates as needed."""
    for key in path[:-1]:
        d = d.setdefault(key, {})
    d[path[-1]] = value


def build_params(node):
    """Reconstruct nested H5P params from flat RST options."""
    params = {}

    for option_name, value in node.get('h5p_options', {}).items():
        entry = _OPTION_MAP.get(option_name)
        if entry is None:
            continue
        path, is_negated = entry
        if value is None:
            # directives.flag returns None when present
            value = not is_negated
        elif is_negated and isinstance(value, bool):
            value = not value
        _set_nested(params, path, value)
{% if body_mapping %}

    body_text = node.astext()
    if body_text:
        _set_nested(params, _BODY_PATH, body_text)
{% endif %}

    # Collect child node params
    for child in node.children:
        if hasattr(child, 'h5p_entity'):
            entity = child.h5p_entity
            params.setdefault(entity, [])
            if hasattr(child, 'build_params'):
                params[entity].append(child.build_params())

    return params
