#!/usr/bin/env python

import argparse
import importlib
import sys

from bacalhau.corpus import Corpus


def main():
    description = 'Generate a topic hierarchy for a corpus. By default outputs an SVG representation of the tree.'
    parser = argparse.ArgumentParser(description=description)
    corpus_path_help = 'path to the directory containing the corpus files'
    parser.add_argument('corpus_path', help=corpus_path_help)
    output_help = 'file to output to'
    parser.add_argument('-o', '--output', default=sys.stdout, help=output_help,
                        type=argparse.FileType('w'))
    document_class_help = 'Python class to use for handling corpus files'
    parser.add_argument('-d', '--document',
                        default='bacalhau.tei_document.TEIDocument',
                        help=document_class_help)
    json_help = 'output the topic tree serialised as JSON'
    parser.add_argument('-j', '--json', action='store_true', help=json_help)
    number_help = 'number of terms to be used from each text'
    parser.add_argument('-n', '--number', default=10, help=number_help,
                        type=int)
    raw_help = 'do not compress the topic tree'
    parser.add_argument('-r', '--raw', action='store_true', help=raw_help)
    xpath_help = 'XPath expression to extract individual texts from XML corpus files'
    parser.add_argument('-x', '--xpath', help=xpath_help)
    args = parser.parse_args()
    document_class = get_document_class(args.document)
    kwargs = {}
    if args.xpath:
        kwargs['xpath'] = args.xpath
    corpus = Corpus(args.corpus_path, document_class, **kwargs)
    tree = corpus.generate_topic_tree(n_terms=args.number)
    if not args.raw:
        tree.compress()
    if args.json:
        tree.to_json(args.output)
    else:
        tree.render(args.output)

def get_document_class (document_class_name):
    # QAZ: Really?
    parts = document_class_name.split('.')
    module_name = '.'.join(parts[:-1])
    class_name = parts[-1]
    module = importlib.import_module(module_name)
    return module.__dict__[class_name]


if __name__ == "__main__":
    main()
