#!/usr/bin/env python2.7

import logging
from skbio.tree import TreeNode
import os
import sys
import argparse
from string import split as _

try:
    import tree2tax.threshold_finder
except ImportError:
    sys.path.append(os.path.join(os.path.dirname(os.path.realpath(__file__)),'..'))
from tree2tax.threshold_finder import ThresholdFinder


parser = argparse.ArgumentParser(description='''--- threshold_estimator --- find thresholds for a tree for particular taxonomic ranks e.g. distance between families that are in the same order''')
parser.add_argument('-t', '--tree', help='newick format tree file to partition', required=True)
parser.add_argument('--debug', help='output debug information', action="store_true")

args = parser.parse_args()

if args.debug:
    logging.basicConfig(level=logging.DEBUG)
else:
    logging.basicConfig(level=logging.INFO)

threshold_names = _('k p c o f g s')

# Read in the tree
logging.info("Reading annotated tree file..")
tree = TreeNode.read(args.tree)
logging.info("Read in tree with %s tips" % tree.count(tips=True))

for i, level_prefix in enumerate(threshold_names):
    if i==0: continue
    examples = ThresholdFinder().find_examples(tree, threshold_names[i-1], level_prefix)
    for e in examples:
        print "\t".join([threshold_names[i-1],
                         level_prefix,
                         e.parent_node.name,
                        e.daughter_node1.name,
                        e.daughter_node2.name,
                        str(e.distance)])