"""Sphinx extension: Yodl var() → :var:`...` → HTML <var> / man \\fI / texinfo @var."""

from docutils import nodes
from docutils.parsers.rst import Directive, directives, roles


class zsh_var(nodes.Inline, nodes.TextElement):
    """Inline metavariable (Yodl var() / HTML5 <var>)."""


def _var_role(role, rawtext, text, lineno, inliner, options=None, content=None):
    return [zsh_var(rawtext, text)], []


def _visit_var_html(self, node):
    self.body.append(self.starttag(node, "var", ""))


def _depart_var_html(self, node):
    self.body.append("</var>")


def _visit_var_man(self, node):
    self.body.append("\\fI")


def _depart_var_man(self, node):
    self.body.append("\\fP")


def _visit_var_texinfo(self, node):
    self.body.append("@var{")


def _depart_var_texinfo(self, node):
    self.body.append("}")


def _visit_var_passthrough(self, node):
    pass


def _depart_var_passthrough(self, node):
    pass


class ZshModuleMeta(Directive):
    """Scrape-only metadata on module fragments; produces no doctree nodes."""

    has_content = False
    required_arguments = 0
    optional_arguments = 0
    option_spec = {
        "name": directives.unchanged_required,
        "summary": directives.unchanged_required,
    }

    def run(self):
        return []


def setup(app):
    roles.register_local_role("var", _var_role)
    app.add_node(
        zsh_var,
        html=(_visit_var_html, _depart_var_html),
        man=(_visit_var_man, _depart_var_man),
        texinfo=(_visit_var_texinfo, _depart_var_texinfo),
        text=(_visit_var_passthrough, _depart_var_passthrough),
        latex=(_visit_var_passthrough, _depart_var_passthrough),
    )
    app.add_directive("zsh-module-meta", ZshModuleMeta)
    return {
        "version": "1.0",
        "parallel_read_safe": True,
        "parallel_write_safe": True,
    }
