import sys
import re

category_file = sys.argv[1] 
category_tree_file = sys.argv[2] 

cat = {}
with open(category_file, 'r') as f:
    for line in f:
        line_split = line.rstrip('\n').split(':')
        cat[line_split[1].replace('_', ' ')] = line_split[0]


stack = []
with open(category_tree_file, 'r') as f:
    with open('cat-cat.txt', 'w') as w:
        for line in f:
            line_split = line.rstrip('\n')
            line_split = line_split.split('|')[0].replace('[[:Category:','')
            pattern = '#*'
            p = re.compile(pattern)
            level = len(p.match(line_split).group())
            if level > 0:
                pair = (level, re.split('#*', line_split)[1].strip(' '))
            elif level == 0:
                pair = (level, re.split('#*', line_split)[0].strip(' '))
            if len(stack) == 0 or level > stack[len(stack) - 1][0]:
                if len(stack) > 0:
                    peak_pair = stack[len(stack) - 1]
                    #w.writelines(str(cat[peak_pair[1]]) + '->' + str(cat[pair[1]]) + '\n')
                    w.writelines(peak_pair[1] + '->' + pair[1] + '\n')
                stack.append(pair)
            else:
                while level <= stack[len(stack) - 1][0]:
                    stack.pop()
                peak_pair = stack[len(stack) - 1]
                w.writelines(peak_pair[1] + '->' + pair[1] + '\n')
                stack.append(pair)

#print(stack)