#!/data/data/com.termux/files/usr/bin/env python3

# ---------------------- faust2atomsnippets -----------------------
# Usage: `faust2atomsnippets *.lib > faust-library.cson`
#        `faust2atomsnippets -j *.lib > faust-library.json`
#
# Creates an atom snippets for each function in a library
# Assumes the same format than faust2md.
# With -j, creates VS Code snippets (JSON), with the first sentence
# of the documentation of each function as description. The prefix is
# the qualified name (`fi.lowpass`): VS Code then offers the snippet for
# `lowp` as well as for `fi.lowp`, and replaces the `fi.` already typed.
#
# The generated snippets file as the following structure:
#
# '.source.faust':
#       'noise':
#               'prefix': 'noise'
#               'body': 'no.noise'
#       ...
#
# The format of a title is :
#       //############# Title Name #################
#       //  markdown text....
#       //  markdown text....
#       //##########################################
#
# The format of a section is :
#       //============== Section Name ==============
#       //  markdown text....
#       //  markdown text....
#       //==========================================
#
# The format of a comment is :
#       //-------------- foo(x,y) ------------------
#       //  markdown text....
#       //  markdown text....
#       //------------------------------------------
# everything else is considered faust code.
# The translation is the following:
#   ## foo(x,y)
#       markdown text....
#       markdown text....
# --------------------------------------------------------

import sys
import os
import re
import json
import getopt


def usage(prog):
    print("usage: %s [-h|--help] [-s|-j] [-t tabsize] *.lib > faust-library.cson" % (prog,))
    print("  -h, --help    Show this help and exit")
    print("  -s            Simplified output (prefix+body only)")
    print("  -j            VS Code snippets (JSON)")
    print("  -t tabsize    Set tab size when expanding tabs in comments")


# Outdent a comment line by n characters in
# order to remove the prefix "//   "
def outdent(line, n):
    if len(line) <= n:
        return "\n"
    else:
        return line[n:]


# Match the 2-characters prefix of a library.
# We want to extract "no" from "...prefix is `no`..."
def matchPrefixName(line):
    return re.search(r"^.*prefix is .(..).*", line)


# Match a prefix sentence cut at the end of the line,
# the prefix being on the next line: "...prefix is\n// `rm`"
def matchPrefixAtEnd(line):
    return re.search(r"prefix is\s*$", line)


# Match the 2-characters prefix at the start of a comment line
def matchPrefixNextLine(line):
    return re.search(r"^\s*//\s*`(..)`", line)


# Match the first line of a title
# of type "//#### Title ####
# at least 3 * are needed
def matchBeginTitle(line):
    return re.search(r"^\s*//#{3,}\s*([^#]+)#{3,}", line)


# Match the last line of a title
# of type "//#######"
# or a blank line
def matchEndTitle(line):
    return re.search(r"^\s*((//#{3,})|(\s*))$", line)


# Match the first line of a section
# of type "//==== Section ===="
# at least 3 = are needed
def matchBeginSection(line):
    return re.search(r"^\s*//={3,}\s*([^=]+)={3,}", line)


# Match the last line of a section
# of type "//======="
# or a blank line
def matchEndSection(line):
    return re.search(r"^\s*((//={3,})|(\s*))$", line)


# Match the first line of a comment and return the function names
# of type "//--- `(aa.)foo` ----" or "//--- `(aa.)foo`, `(aa.)bar` ----"
# at least 3 - are needed
def matchBeginComment(line):
    if re.search(r"^\s*//-{3,}\s*`[^`]+`.*-{3,}\s*$", line):
        return re.findall(r"`(?:\([a-z]{2}\.\))?([^-`]+)`", line)
    return []


# Match the last line of a comment
# of type "//-----------------"
# or a blank line
def matchEndComment(line):
    return re.search(r"^\s*((//-{3,})|(\s*))$", line)


# Compute the indentation of a line,
# that is the position of the first word character
# after "//   "
def indentation(line):
    matchComment = re.search(r"(^\s*//\s*\w)", line)
    if matchComment:
        return len(matchComment.group(1)) - 1
    else:
        return 0


# Indicates if a line is a comment
def isComment(line):
    matchComment = re.search(r"^\s*//", line)
    if matchComment:
        return 1
    else:
        return 0

#
# THE PROGRAM STARTS HERE
#
tabsize = 4  # tabsize used for expanding tabs
mode = 0  # 0: in code; 1: in md-comment
idt = 0  # indentation retained to outdent comment lines
simplified = 0  # 0: full mode; 1: body only
vscode = 0  # 1: VS Code snippets (JSON)
libprefix = "xx"  #
snippets = {}  # VS Code snippets, by qualified name
current = []  # VS Code snippets of the comment being read
paragraph = []  # first paragraph of the comment being read


# Set the description of the VS Code snippets of the comment just read,
# the first sentence of its first paragraph
def describe(current, paragraph, file):
    text = re.split(r"(?<=[.!?])\s+(?=[A-Z`])", " ".join(paragraph))[0]
    for s in current:
        s["description"] = "%s: %s" % (file, text) if text else file

# Analyze command line arguments
try:
    opts, args = getopt.getopt(sys.argv[1:], "hsjt:cf", ["help"])
except getopt.error as e:
    print(e.msg)
    usage(sys.argv[0])
    sys.exit(1)
help_requested = any(optname in ("-h", "--help") for optname, _ in opts)
if not args and not help_requested:
    usage(sys.argv[0])
    sys.exit(1)
for optname, optvalue in opts:
    if optname == "-t":
        tabsize = int(optvalue)
    if optname == "-s":
        simplified = 1
    if optname == "-j":
        vscode = 1
    if optname in ("-h", "--help"):
        usage(sys.argv[0])
        sys.exit(0)

# Process all the files and print the documentation on the standard output
if simplified and not vscode:
    sys.stdout.write("let gFaustLibSnippets = ")
    sep = "["
elif not vscode:
    print("'.source.faust':")

for file in args:
    # each library declares its own prefix, the first one found is kept
    libprefix = "xx"
    prefixFound = 0
    prefixPending = 0
    libname = os.path.basename(file)
    with open(file) as f:
        for text in f:
            line = text.expandtabs(tabsize)
            if not prefixFound:
                matchPrefix = matchPrefixName(line)
                if prefixPending:
                    matchPrefix = matchPrefixNextLine(line)
                    prefixPending = 0
                if matchPrefix:
                    libprefix = matchPrefix.group(1)
                    prefixFound = 1
                elif matchPrefixAtEnd(line):
                    prefixPending = 1
            if isComment(line) == 0:
                if mode == 1:
                    # we are closing a md-comment
                    mode = 0
                    describe(current, paragraph, libname)
                    current = []
            else:
                if mode == 0:  # we are in code
                    matchComment = matchBeginComment(line)
                    matchSection = matchBeginSection(line)
                    matchTitle = matchBeginTitle(line)
                    for foo in matchComment:
                        name = "%s.%s" % (libprefix, foo)
                        if vscode:
                            if name not in snippets:
                                snippets[name] = {"prefix": name, "body": name}
                                current.append(snippets[name])
                        elif simplified:
                            sys.stdout.write("%s '%s'" % (sep, name))
                            sep = ","
                        else:
                            print("\t'%s':" % (foo,))
                            print("\t\t'prefix': '%s'" % (foo,))
                            print("\t\t'body': '%s'" % (name,))
                    if matchComment or matchSection or matchTitle:
                        mode = 1  # we just started a md-comment
                        idt = 0  # we have to measure the indentation
                        paragraph = []
                        inParagraph = 1
                else:
                    # we are in a md-comment
                    if idt == 0:
                        # we have to measure the indentation
                        idt = indentation(line)
                    # check end of md-comment
                    matchComment = matchEndComment(line)
                    matchSection = matchEndSection(line)
                    matchTitle = matchEndTitle(line)
                    if matchComment or matchSection or matchTitle:
                        # end of md-comment switch back to mode O
                        mode = 0
                        describe(current, paragraph, libname)
                        current = []
                    elif inParagraph:
                        # keep the first paragraph, up to a blank line or a heading
                        words = line.strip()[2:].strip()
                        if words == "" or words.startswith("#"):
                            inParagraph = 0 if paragraph or words.startswith("#") else 1
                        else:
                            paragraph.append(words)
    describe(current, paragraph, libname)
    current = []
    mode = 0

if vscode:
    print(json.dumps(snippets, indent=2, ensure_ascii=False))
elif simplified:
    print(" ];")
