#!/usr/bin/python3
import json
import sys
import argparse

def get_busco_lineage(taxid,fdata):
    lineage=None
    with open(fdata,'r') as fh:
        levels2busco = json.load(fh)
        
        if taxid in levels2busco:
            lineage=levels2busco[taxid][1]
    return lineage

def get_busco_taxid(lineage,fdata):
    taxid=None
    with open(fdata,'r') as fh:
        levels2busco = json.load(fh)
    
        for e in levels2busco.items():
            lin=e[1][1]
            if lin == lineage:
                taxid = int(e[1][0])
                break
    
    return taxid


parser = argparse.ArgumentParser(description='get busco lineage string and taxid')
parser.add_argument('-i', '--input',    dest='input', help='taxid of level OR busco label', required=True)
parser.add_argument('-d', '--data',     dest='data',  help='levels to busco name json', required=True)
options = parser.parse_args()

if options.input.isdecimal():
    busco_lineage = get_busco_lineage(options.input,options.data)
    busco_taxid   = options.input
    if busco_lineage is None:
        print('error: no busco lineage was found for taxid {} in file {}'.format(options.input,options.data),file=sys.stderr)
else:
    busco_taxid   = get_busco_taxid(options.input,options.data)
    busco_lineage = options.input
    if busco_taxid is None:
        print('error: no taxid was found for busco lineage {} in file {}'.format(options.input,options.data),file=sys.stderr)
    
if busco_lineage is None or busco_taxid is None:
    sys.exit(255)
else:
    print('%s %s'%(busco_lineage,busco_taxid))



