#!/usr/local/bin/python3.12
"""
rest2html - A small wrapper file for parsing ReST files at GitHub.

Written in 2008 by Jannis Leidel <jannis@leidel.info>

Brandon Keepers <bkeepers@github.com>
Bryan Veloso <bryan@revyver.com>
Chris Wanstrath <chris@ozmm.org>
Dave Abrahams <dave@boostpro.com>
Garen Torikian <garen@github.com>
Gasper Zejn <zejn@kiberpipa.org>
Michael Jones <m.pricejones@gmail.com>
Sam Whited <sam@samwhited.com>
Tyler Chung <zonyitoo@gmail.com>
Vicent Marti <tanoku@gmail.com>

To the extent possible under law, the author(s) have dedicated all copyright
and related and neighboring rights to this software to the public domain
worldwide. This software is distributed without any warranty.

You should have received a copy of the CC0 Public Domain Dedication along with
this software. If not, see <http://creativecommons.org/publicdomain/zero/1.0/>.
"""

__author__ = "Jannis Leidel"
__license__ = "CC0"
__version__ = "0.2"

import sys
import os

# This fixes docutils failing with unicode parameters to CSV-Table. The -S
# switch and the following 3 lines can be removed after upgrading to python 3.
if sys.version_info[0] < 3:
    reload(sys)
    sys.setdefaultencoding('utf-8')

import site

try:
    import locale
    locale.setlocale(locale.LC_ALL, '')
except:
    pass

import codecs
import io

from docutils import nodes, statemachine
from docutils.parsers.rst import directives, roles
from docutils.parsers.rst.directives.body import CodeBlock
from docutils.core import publish_parts
from docutils.writers.html4css1 import Writer, HTMLTranslator

SETTINGS = {
    '_disable_config': True,
    'cloak_email_addresses': False,
    'file_insertion_enabled': False,
    'raw_enabled': False,
    'strip_comments': True,
    'doctitle_xform': True,
    'sectsubtitle_xform': True,
    'initial_header_level': 2,
    'report_level': 5,
    'syntax_highlight': 'none',
    'math_output': 'latex',
    'field_name_limit': 50,
    'auto_id_prefix': 'id', # for now, stay backward compatible with older RST content
}


class DoctestDirective(CodeBlock):
    """Render Sphinx 'doctest:: [group]' blocks as 'code:: python'
    """

    def run(self):
        """Discard any doctest group argument, render contents as python code
        """
        self.arguments = ['python']
        return super(DoctestDirective, self).run()


class PlantumlDirective(CodeBlock):
    """
    Render 'plantuml::' blocks as 'code:: plantuml', so they will be
    picked up in GitLab by the generic Banzai::Filter::PlantumlFilter
    """

    option_spec = CodeBlock.option_spec.copy()
    option_spec.update({
        'caption': directives.unchanged
    })

    def run(self):
        self.arguments = ['plantuml']
        node = super(PlantumlDirective, self).run()

        if 'caption' in self.options:
            # create an anonymous container to parse the caption content
            container = nodes.Element()
            content = statemachine.StringList([self.options['caption']])
            self.state.nested_parse(content, self.content_offset, container)
            caption = nodes.caption(self.options['caption'], '', *container)

            node.append(caption)

        return node


class GitHubHTMLTranslator(HTMLTranslator, object):

    # removes the <div class="document"> tag wrapped around docs
    # see also: http://bit.ly/1exfq2h (warning! sourceforge link.)
    def depart_document(self, node):
        HTMLTranslator.depart_document(self, node)
        self.html_body.pop(0)  # pop the starting <div> off
        self.html_body.pop()   # pop the ending </div> off

    # technique for visiting sections, without generating additional divs
    # see also: http://bit.ly/NHtyRx
    # the a is to support ::contents with ::sectnums: http://git.io/N1yC
    def visit_section(self, node):
        id_attribute = node.attributes['ids'][0]
        self.body.append('<a name="%s"></a>\n' % id_attribute)
        self.section_level += 1

    def depart_section(self, node):
        self.section_level -= 1

    def visit_literal_block(self, node):
        classes = node.attributes['classes']

        if len(classes) >= 2 and classes[0] == 'code':
            language = classes[1]
            del classes[:]
            self.body.append(self.starttag(node, 'pre'))
            self.body.append(self.starttag(node, 'code', suffix='', lang=language))
        else:
            self.body.append(self.starttag(node, 'pre'))
            self.body.append(self.starttag(node, 'code', suffix=''))

    def depart_literal_block(self, node):
        self.body.append('</code>')

        return super(GitHubHTMLTranslator, self).depart_literal_block(node)

    # always wrap two-backtick rst inline literals in <code>, not <tt>
    # this also avoids the generation of superfluous <span> tags
    def visit_literal(self, node):
        self.body.append(self.starttag(node, 'code', suffix=''))

    def depart_literal(self, node):
        self.body.append('</code>')

    def visit_table(self, node):
        classes = ' '.join(['docutils', self.settings.table_style]).strip()
        self.body.append(
            self.starttag(node, 'table', CLASS=classes))

    def depart_table(self, node):
        self.body.append('</table>\n')

    def depart_image(self, node):
        uri = node['uri']
        ext = os.path.splitext(uri)[1].lower()
        # we need to swap RST's use of `object` with `img` tags
        # see http://git.io/5me3dA
        if ext == ".svg":
            # preserve essential attributes
            atts = {}
            for attribute, value in node.attributes.items():
                # we have no time for empty values
                if value:
                    if attribute == "uri":
                        atts['src'] = value
                    else:
                        atts[attribute] = value

            # toss off `object` tag
            self.body.pop()
            # add on `img` with attributes
            self.body.append(self.starttag(node, 'img', **atts))
        HTMLTranslator.depart_image(self, node)


def kbd(name, rawtext, text, lineno, inliner, options=None, content=None):

    return [nodes.raw('', '<kbd>%s</kbd>' % text, format='html')], []


def main():
    """
    Parses the given ReST file or the redirected string input and returns the
    HTML body.

    Usage: rest2html < README.rst
           rest2html README.rst
    """
    try:
        text = codecs.open(sys.argv[1], 'r', 'utf-8').read()
    except IOError:  # given filename could not be found
        return ''
    except IndexError:  # no filename given
        if sys.version_info[0] < 3: # python 2.x
            text = sys.stdin.read()
        else: # python 3
            input_stream = io.TextIOWrapper(sys.stdin.buffer, encoding='utf-8')
            text = input_stream.read()

    writer = Writer()
    writer.translator_class = GitHubHTMLTranslator

    roles.register_canonical_role('kbd', kbd)

    # Render source code in Sphinx doctest blocks
    directives.register_directive('doctest', DoctestDirective)

    # Render source code in Sphinx plantuml blocks
    # Also support uml:: directive for compatibility with sphinxcontrib-plantuml
    directives.register_directive('plantuml', PlantumlDirective)
    directives.register_directive('uml', PlantumlDirective)

    parts = publish_parts(text, writer=writer, settings_overrides=SETTINGS)
    if 'html_body' in parts:
        html = parts['html_body']

        # publish_parts() in python 2.x return dict values as Unicode type
        # in py3k Unicode is unavailable and values are of str type
        if isinstance(html, str):
            return html
        else:
            return html.encode('utf-8')
    return ''

if __name__ == '__main__':
    if sys.version_info[0] < 3: # python 2.x
        sys.stdout.write("%s%s" % (main(), "\n"))
    else: # python 3
        output_stream = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')
        output_stream.write("%s%s" % (main(), "\n"))
    sys.stdout.flush()
