#!/bin/python

import os
import sys
import argparse

def read_list(filename):
    ids=[]
    with open(filename,'r') as fh:
        for line in fh:
            line = line.strip().rstrip('\n')
            if len(line)==0:
                continue
            if line[0]=='#':
                continue
            ids.append(line)
            
    ids.sort()
    return ids

def intersection(lst1, lst2): 
    rval = list(set(lst1) & set(lst2))
    rval.sort()
    return rval

def uniqueFirst(lst1, lst2): 
    rval = list(set(lst1) - set(lst2))
    rval.sort()
    return rval

def create_pairs(ids,diagonal):
    n = len(ids)
    iofs = 1
    if diagonal:
        iofs=0
    for i in range(0,n):
        idA = ids[i]
        for j in range(i+iofs,n):
            idB = ids[j]
            if idA<idB:
                print('{} {}'.format(idA,idB))
            else:
                print('{} {}'.format(idB,idA))

def create_pairsAB(idsA,idsB):
    for idA in idsA:
        for idB in idsB:
            if idA<idB:
                print('{} {}'.format(idA,idB))
            else:
                print('{} {}'.format(idB,idA))
        
def basename(fname):
    r = os.path.splitext(os.path.basename(fname))
    return r[0]

def process(froot,fchildren,diagonal):
    #print('root : {}'.format(froot))
    root = read_list(froot)
    rootName = 'root({})'.format(basename(froot))
    unique = root
    children = []
    chNames=[]
    if fchildren is not None:
        # read all children and produce the list of unique ids in root
        for fc in fchildren:
            c = read_list(fc)
            if len(c)==0:
                print('# empty child at {}'.format(fc))
                continue
            # update unique list
            unique = uniqueFirst( unique,c )
            # save child
            children.append(c)
            chNames.append(basename(fc))

    # create pairs for unique root
    print('# {} vs {} ; N={}x{}'.format(rootName,rootName,len(unique),len(unique)))
    create_pairs(unique,diagonal)
        
    for i in range(0,len(children)):
        cA = children[i]
        chN = chNames[i]
        
        # create pairs between unique root and child
        print('# {} vs {} ; N={}x{}'.format(rootName,chN,len(unique),len(cA)))
        create_pairsAB(cA,unique)
        
        # create pairs between children
        for j in range(i+1,len(children)):
            cB = children[j]
            print('# {} vs {} ; N={}x{}'.format(chNames[i],chNames[j],len(cA),len(cB)))
            create_pairsAB(cA,cB)
    
parser = argparse.ArgumentParser(description='Extract taxids in BRH file')

parser.add_argument('-r', '--root', dest='root',
                    help='root node', metavar='FILE', required=True)
parser.add_argument('-c', '--child', dest='child',help='child node(s)', nargs='+')
parser.add_argument('-d', '--diagonal', dest='diagonal', help='include diagonal', action='store_true', required=False, default=False)
options = parser.parse_args()

process(options.root,options.child,options.diagonal)
