#! /usr/bin/env python

from memory_profiler import profile
from argparse import ArgumentParser
from graph import WordGraph
from io import IO

__author__ = 'barryhennessy'


def run(args):
    """Runs the core of the script; builds the graph and performs the required
    search type

    Split out as a separate function to facilitate optional profiling

    :param args: the arguments object generated by the script call
    """

    io = IO()

    reader = io.read_dictionary(args.dictionary_path)

    graph = WordGraph()

    for word in reader:
        graph.add(word)

    if args.all_paths:
        paths = graph.find_all_paths(args.word_from, args.word_to)
        for path in paths:
            print io.format_word_path(path)
    else:
        path = graph.find_path(args.word_from, args.word_to)
        print io.format_word_path(path)

if __name__ == '__main__':
    parser = ArgumentParser()

    parser.add_argument("dictionary_path", type=str)

    parser.add_argument(
        "--from",
        help="the word from which to start your search",
        required=True,
        dest="word_from"
    )

    parser.add_argument(
        "--to",
        help="the destination word",
        required=True,
        dest="word_to"
    )

    parser.add_argument(
        "--mem-profile",
        action='store_true',
        help="profile the script to examine it's memory performance"
    )

    parser.add_argument(
        "--all-paths",
        action='store_true',
        help="search for all possible paths"
    )

    args = parser.parse_args()

    if args.mem_profile:
        profile(run)(args)
    else:
        run(args)
