#!/usr/bin/env python
'''
parse, navigate, and convert vms .help files

Parses, navigates, and converts vms .help files to JSON.

Example vms .help file:
-----------------------------------------------------------------------
1 Top Level
 Top level contents.

2 Subsection One of Top Level
 The first subsection of the top level section.

3 Subsection One of Subsection One of Top Level
 The first subsection of the first subsection of the top level section.
 
2 Subsection Two of Top Level
 The second subsection of the top level section.
-----------------------------------------------------------------------
'''

import sys
import os
import argparse
import textwrap
import re
import json

__author__ = 'Stephen Norum <snorum@slac.stanford.edu>'
__version__ = '1.1'
__all__ = ['HelpNode', 'parse_help_file', 'navigate_help_tree']


def indent(string, amount=4):
    line_start_re = re.compile(r'^', re.MULTILINE)
    return re.sub(line_start_re, ' ' * amount, string)


class HelpNode(object):
    def __init__(self, level=0, parent=None, title='root', text=None, sections=None, ordered_keys=None):
        self.level = level
        self.parent = parent
        self.text = [] if text is None else text
        self.ordered_keys = [] if ordered_keys is None else ordered_keys
        self.sections = {} if sections is None else sections
        self.title = title
    
    def __str__(self):
        out = []
        out.append('{0.title}'.format(self))
        for key in self.ordered_keys:
            out.append(indent(str(self.sections[key])))
        return '\n'.join(out)
    
    @property
    def help_text(self):
        return textwrap.dedent(''.join(self.text)).rstrip()
    
    def add_section(self, level, title):
        new_section = HelpNode(level=level, title=title, parent=self)
        self.sections[title] = new_section
        self.ordered_keys.append(title)
        return new_section

    @property
    def simple_dict(self):
        out = {}
        out['text'] = self.help_text
        out['key_order'] = self.ordered_keys
        out['sections'] = {}
        for key in self.ordered_keys:
            out['sections'][key] = self.sections[key].simple_dict
        return out

    def json_dumps(self):
        help_dict = self.simple_dict
        out = {
            'version': 1,
            'sections': help_dict
        }
        return json.dumps(out, sort_keys=True, indent=4)
    
    def rst(self):
        headers = ['*', '=', '-', '~', '.', '`']
        out = []
        if self.level == 0:
            out.append(textwrap.dedent('''
                .. About This Document
                .. ===================
                ..
                .. This document is formatted as reStructuredText.
                .. See http://docutils.sourceforge.net/rst.html
                .. for more information.
                ..
                ..
                .. title:: VMS Help
                .. contents:: Table of Contents
                .. sectnum::
            '''))
        else:
            out.append('\n\n{0}'.format(self.title))
            out.append(headers[self.level] * len(self.title))
        if self.help_text:
            out.append('\n::\n')
            out.append(indent(self.help_text))
            out.append('')
        for key in self.ordered_keys:
            out.append(self.sections[key].rst())
        return '\n'.join(out)

def parse_help_file(help_file_contents, root=None):
    '''
    Return parsed HelpNode tree from help_file_contents data.
    '''
    section_header_re = re.compile(
        r'''
            (?P<level>\d+)  # section level
            \s+             # white space delimeter
            (?P<title>.*)   # section title
        ''',
        re.VERBOSE
    )

    if root is None:
        root = HelpNode()
        
    current_section = root
    
    for line in help_file_contents:
        m = section_header_re.match(line)
        if m:
            level = int(m.group('level'))
            title = str(m.group('title')).strip()
            
            while level <= current_section.level:
                current_section = current_section.parent
                        
            if level == current_section.level:
                current_section = current_section.parent.add_section(level, title)
            elif level == current_section.level + 1:
                current_section = current_section.add_section(level, title)
            else:
                raise(ValueError('Bad level ({0}) for "{1}"'.format(level, title)))
        else:
            current_section.text.append(line)
        
    return root


def navigate_help_tree(help_tree):
    current_section = help_tree
    while True:
        if current_section.ordered_keys:
            title = 'Sections'
            print
            print title
            print '-' * len(title)
            for i, key in enumerate(current_section.ordered_keys):
                print '{0:3}) {1}'.format(i, key)
            print
            print 'View Additional Help On: ', 
            choice = sys.stdin.readline().strip()
            if not choice:
                if current_section.parent is None:
                    break
                else:
                    current_section = current_section.parent
                    continue
            if choice.lower() == 'q':
                break                
            try:
                chosen_key = current_section.ordered_keys[int(choice)]
            except (ValueError, IndexError):
                print
                print 'Invalid choice'
                continue
            
            print 
            print chosen_key
            print '=' * len(chosen_key)
            current_section = current_section.sections[chosen_key]
            print current_section.help_text
        else:
            current_section = current_section.parent
            print
            print 'Press Enter To Continue', 
            sys.stdin.readline()


def process_options(argv=None):
    if argv is None:
        argv = sys.argv[1:]
    
    parser = argparse.ArgumentParser()
    parser.add_argument('help_files', metavar='HELP_FILE', nargs='+', help='vms .help file')
    parser.add_argument('-t', '--toc', action='store_true', help='show help file table of contents')
    parser.add_argument('-j', '--json', action='store_true', help='export help files as json')
    parser.add_argument('-r', '--rst', action='store_true', help='export help files as reStructuredText')
    args = parser.parse_args(argv)
    
    return args


def main(argv=None):
    if argv is None:
        argv = sys.argv[1:]
        
    args = process_options(argv)

    help_tree = None
    for help_file in args.help_files:
        with open(help_file) as f:
            help_tree = parse_help_file(f, help_tree)

    if args.toc:
        print str(help_tree)
        return 0
    elif args.json:
        print help_tree.json_dumps()
        return 0
    elif args.rst:
        print help_tree.rst()
        return 0
    
    try:
        navigate_help_tree(help_tree)
    except KeyboardInterrupt:
        pass

    return 0


if __name__ == '__main__':
    status = main()
    sys.exit(status)
