#!/usr/bin/env python3
#
# updateDocumentToC.py
#
# Insert table of contents at top of Catch markdown documents.
#
# This script is distributed under the GNU General Public License v3.0
#
# It is based on markdown-toclify version 1.7.1 by Sebastian Raschka,
# https://github.com/rasbt/markdown-toclify
#
from  __future__  import print_function
import argparse
import glob
import os
import re
import sys
from scriptCommon import catchPath
# Configuration:
minTocEntries = 4
headingExcludeDefault = [1,3,4,5]  # use level 2 headers for at default
headingExcludeRelease = [1,3,4,5]  # use level 1 headers for release-notes.md
documentsDefault = os.path.join(os.path.relpath(catchPath), 'docs/*.md')
releaseNotesName = 'release-notes.md'
contentTitle = '**Contents**'
contentLineNo = 4
contentLineNdx = contentLineNo - 1
# End configuration
VALIDS = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_-&'
def readLines(in_file):
    """Returns a list of lines from a input markdown file."""
    with open(in_file, 'r') as inf:
        in_contents = inf.read().split('\n')
    return in_contents
def removeLines(lines, remove=('[[back to top]', ' tags."""
    if not remove:
        return lines[:]
    out = []
    for l in lines:
        if l.startswith(remove):
            continue
        out.append(l)
    return out
def removeToC(lines):
    """Removes existing table of contents starting at index contentLineNdx."""
    if not lines[contentLineNdx ].startswith(contentTitle):
        return lines[:]
    result_top = lines[:contentLineNdx]
    pos = contentLineNdx + 1
    while lines[pos].startswith('['):
        pos = pos + 1
    result_bottom = lines[pos + 1:]
    return result_top + result_bottom
def dashifyHeadline(line):
    """
    Takes a header line from a Markdown document and
    returns a tuple of the
        '#'-stripped version of the head line,
        a string version for  anchor tags,
        and the level of the headline as integer.
    E.g.,
    >>> dashifyHeadline('### some header lvl3')
    ('Some header lvl3', 'some-header-lvl3', 3)
    """
    stripped_right = line.rstrip('#')
    stripped_both = stripped_right.lstrip('#')
    level = len(stripped_right) - len(stripped_both)
    stripped_wspace = stripped_both.strip()
    # GitHub's sluggification works in an interesting way
    # 1) '+', '/', '(', ')' and so on are just removed
    # 2) spaces are converted into '-' directly
    # 3) multiple -- are not collapsed
    dashified = ''
    for c in stripped_wspace:
        if c in VALIDS:
            dashified += c.lower()
        elif c.isspace():
            dashified += '-'
        else:
            # Unknown symbols are just removed
            continue
    return [stripped_wspace, dashified, level]
def tagAndCollect(lines, id_tag=True, back_links=False, exclude_h=None):
    """
    Gets headlines from the markdown document and creates anchor tags.
    Keyword arguments:
        lines: a list of sublists where every sublist
            represents a line from a Markdown document.
        id_tag: if true, creates inserts a the  tags (not req. by GitHub)
        back_links: if true, adds "back to top" links below each headline
        exclude_h: header levels to exclude. E.g., [2, 3]
            excludes level 2 and 3 headings.
    Returns a tuple of 2 lists:
        1st list:
            A modified version of the input list where
             anchor tags where inserted
            above the header lines (if github is False).
        2nd list:
            A list of 3-value sublists, where the first value
            represents the heading, the second value the string
            that was inserted assigned to the IDs in the anchor tags,
            and the third value is an integer that represents the headline level.
            E.g.,
            [['some header lvl3', 'some-header-lvl3', 3], ...]
    """
    out_contents = []
    headlines = []
    for l in lines:
        saw_headline = False
        orig_len = len(l)
        l_stripped = l.lstrip()
        if l_stripped.startswith(('# ', '## ', '### ', '#### ', '##### ', '###### ')):
            # comply with new markdown standards
            # not a headline if '#' not followed by whitespace '##no-header':
            if not l.lstrip('#').startswith(' '):
                continue
            # not a headline if more than 6 '#':
            if len(l) - len(l.lstrip('#')) > 6:
                continue
            # headers can be indented by at most 3 spaces:
            if orig_len - len(l_stripped) > 3:
                continue
            # ignore empty headers
            if not set(l) - {'#', ' '}:
                continue
            saw_headline = True
            dashified = dashifyHeadline(l)
            if not exclude_h or not dashified[-1] in exclude_h:
                if id_tag:
                    id_tag = ''\
                              % (dashified[1])
                    out_contents.append(id_tag)
                headlines.append(dashified)
        out_contents.append(l)
        if back_links and saw_headline:
            out_contents.append('[[back to top](#table-of-contents)]')
    return out_contents, headlines
def positioningHeadlines(headlines):
    """
    Strips unnecessary whitespaces/tabs if first header is not left-aligned
    """
    left_just = False
    for row in headlines:
        if row[-1] == 1:
            left_just = True
            break
    if not left_just:
        for row in headlines:
            row[-1] -= 1
    return headlines
def createToc(headlines, hyperlink=True, top_link=False, no_toc_header=False):
    """
    Creates the table of contents from the headline list
    that was returned by the tagAndCollect function.
    Keyword Arguments:
        headlines: list of lists
            e.g., ['Some header lvl3', 'some-header-lvl3', 3]
        hyperlink: Creates hyperlinks in Markdown format if True,
            e.g., '- [Some header lvl1](#some-header-lvl1)'
        top_link: if True, add a id tag for linking the table
            of contents itself (for the back-to-top-links)
        no_toc_header: suppresses TOC header if True.
    Returns  a list of headlines for a table of contents
    in Markdown format,
    e.g., ['        - [Some header lvl3](#some-header-lvl3)', ...]
    """
    processed = []
    if not no_toc_header:
        if top_link:
            processed.append('\n')
        processed.append(contentTitle + '
')
    for line in headlines:
        if hyperlink:
            item = '[%s](#%s)' % (line[0], line[1])
        else:
            item = '%s- %s' % ((line[2]-1)*'    ', line[0])
        processed.append(item + '
')
    processed.append('\n')
    return processed
def buildMarkdown(toc_headlines, body, spacer=0, placeholder=None):
    """
    Returns a string with the Markdown output contents incl.
    the table of contents.
    Keyword arguments:
        toc_headlines: lines for the table of contents
            as created by the createToc function.
        body: contents of the Markdown file including
            ID-anchor tags as returned by the
            tagAndCollect function.
        spacer: Adds vertical space after the table
            of contents. Height in pixels.
        placeholder: If a placeholder string is provided, the placeholder
            will be replaced by the TOC instead of inserting the TOC at
            the top of the document
    """
    if spacer:
        spacer_line = ['\n