#! /usr/bin/env python3

# Copyright 2009-2024 The VOTCA Development Team (http://www.votca.org)
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import argparse
import itertools
import re
import subprocess
from pathlib import Path
from typing import Iterator, List, NamedTuple, Tuple

PROGTITLE = 'THE VOTCA::TOOLS help to doc converter'
VOTCAHEADER = f"""
==================================================
========   VOTCA (http://www.votca.org)   ========
==================================================

{PROGTITLE}

please read and cite: PROJECT_CITATION
and submit bugs to PROJECT_CONTACT
votca_help2doc
"""

AUTHORS = "Written and maintained by the VOTCA Development Team <devs@votca.org>"
COPYRIGHT = """
Copyright 2009-2024 The VOTCA Development Team (http://www.votca.org)

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this  file
except in compliance with the License.  You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

Unless  required by applicable law or agreed to in writing, software distributed under the
License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY  KIND,
either  express  or  implied.   See  the  License  for  the  specific  language  governing
permissions and limitations under the License.
"""
DESCRIPTION = f"""{VOTCAHEADER}
Convert a Votca CLI's help message to RST or GROFF format."""


class Data(NamedTuple):
    """Data class containing the help's section."""
    name: str
    description: str
    examples: str
    options: str
    usage: str
    authors: str = AUTHORS
    copyright: str = COPYRIGHT


def parse_user_arguments() -> argparse.Namespace:
    """Read the user arguments."""
    parser = argparse.ArgumentParser("help2doc", usage=argparse.SUPPRESS,
                                     description=DESCRIPTION, formatter_class=argparse.RawDescriptionHelpFormatter)
    parser.add_argument("-n", "--name", required=True,
                        help="Name of the tool to extract the help message")
    parser.add_argument("-o", "--out", help="Output file", default=None)
    parser.add_argument("-f", "--format", help="Output format",
                        choices=["rst", "groff"], default="rst")
    return parser.parse_args()


def take(it: Iterator[str], n: int) -> List[str]:
    """Take n elements from the Iterator an return them."""
    return [next(it) for _ in range(n)]


def parse_help_message(msg: str, name: str) -> Data:
    """Parse the help message into an intermediate representation."""
    lines = iter(msg.splitlines())
    # Votca logo
    take(lines, 7)
    # remove Compilation info
    lines = take_while_version(lines)

    # description and optional examples
    opts_lines, lines = take_until_options(lines)
    description, examples = read_section_examples(opts_lines)
    description, usage = search_for_usage(description)
    # Options and optional examples
    if examples:
        options = "\n  ".join(filter(lambda x: x, lines))
    else:
        options, examples = read_section_examples(lines)

    options = format_options(options)

    # Search for the `Used external keyword`
    keyword = "Used external"
    if keyword in usage:
        usage_lines = usage.splitlines()
        description += "\n".join(itertools.dropwhile(
            lambda x: keyword not in x, usage_lines))
        usage = "\n".join(itertools.takewhile(
            lambda x: keyword not in x, usage_lines))

    return Data(name, description, examples, options, usage)


def search_for_usage(desc: str) -> Tuple[str, str]:
    """Search for an `usage:` declaration in the description."""
    keywords = {u for u in {"Usage:", "usage:"} if u in desc}
    if not keywords:
        return desc, ""
    else:
        key = keywords.pop()
        data = desc.split(key)
        return data[0], ''.join(data[1:])


def take_while_version(lines: Iterator[str]) -> Iterator[str]:
    """Remove the lines with version on it."""
    value = next(lines)
    if any(key in value for key in {"version", "bugs", "gromacs, 20"}):
        return take_while_version(lines)
    else:
        return itertools.chain([value], lines)


def take_until_options(lines: Iterator[str]) -> Tuple[Iterator[str], Iterator[str]]:
    """Take lines until options."""
    opts = []
    old_lines = []
    for value in lines:
        if not any(x in value for x in {"options:", "arguments:"}):
            opts.append(value)
        else:
            old_lines = itertools.chain([value], lines)
            break
    return iter(opts), iter(old_lines)


def format_options(options: str):
    """Format the options."""
    s = []
    for line in options.splitlines():
        if line.endswith(":"):
            s.append(f"{line}\n")
        else:
            s.append(line)

    return "\n".join(s)


def generate_code_block(name: str) -> str:
    """Generate a code block section."""
    return f"""
{name}
{'*' * len(name)}
.. highlight:: none

::
"""


def format_rst(sec: Data) -> str:
    """Format the section as RST."""
    opts = "\n".join(f"  {x}" for x in sec.options.splitlines())
    examples = "\n".join(f"  {x}" for x in sec.examples.splitlines())

    options_code_block = generate_code_block("OPTIONS")
    examples_code_block = generate_code_block("EXAMPLES")
    usage = f"**Usage:** {sec.usage}" if sec.usage else ""

    return f"""
NAME
****
**{sec.name}** - Part of the VOTCA package

SYNOPSIS
********
**{sec.name}** [OPTIONS]

**{sec.name}** [--help]

{usage}

DESCRIPTION
***********
{sec.description}

{examples_code_block if examples else ""}
{examples}

{options_code_block if opts else ""}
{opts}
"""


def format_groff(sec: Data) -> str:
    """Format the sections in GROFF format."""
    return f""".TH "{sec.name.upper()}" "1" " {sec.name} User Manual" "VOTCA Development Team"
.nh
.ad l

.SH NAME
.PP
\\fB{sec.name}\\fP - Part of the VOTCA package


.SH SYNOPSIS
.PP
\\fB{sec.name}\\fP [OPTIONS]
.PP
\\fB{sec.name}\\fP [--help]


.SH DESCRIPTION
.PP
{sec.description}
{sec.examples}

.SH OPTIONS
.PP

{sec.options}

.SH AUTHORS
.PP
{sec.authors}


.SH COPYRIGHT
.PP
{sec.copyright}
"""


def read_section_examples(lines: Iterator[str]) -> Tuple[str, str]:
    """Check for examples and format them properly."""
    express = re.compile(r'^example', flags=re.IGNORECASE)
    desc = "\n".join(itertools.takewhile(
        lambda x: re.match(express, x) is None, lines))
    # extract example section
    examples = "\n  ".join(lines)
    if examples:
        examples = "  " + examples

    return desc, examples


def convert_help_message(args: argparse.Namespace):
    """Convert help message."""
    path = Path(args.name)
    name = path.stem
    msg = subprocess.check_output(
        f"{path.absolute().as_posix()} --help", shell=True)
    sections = parse_help_message(msg.decode(), name)
    if args.format == "rst":
        data = format_rst(sections)
    else:
        data = format_groff(sections)

    output = args.out if args.out is not None else f"{name}.{args.format}"
    with open(output, 'w') as handler:
        handler.write(data)


def main():
    args = parse_user_arguments()
    convert_help_message(args)


if __name__ == "__main__":
    main()
