import re
import os
import shutil

def filename2Wikilink( s ):
    return '{' + s.replace('_',' ').replace('.gmo','') + '}'

def wikilink2Filename( s, ext='.gmi' ):
    return s.strip("{}").replace(' ','_') + ext

os.chdir('src/')

incoming = {}

for filename in os.listdir():
    if filename.endswith('.gmo'):
        # copy to tmp 
        shutil.copy(filename, '../tmp/'+filename)

#        if filename != 'pages.gmo' and filename != 'index.gmo':
        if filename != 'pages.gmo':
            # convert filename to wikilink
            wikilink=filename2Wikilink(filename)
            if wikilink not in incoming:
                incoming[wikilink] = set()

            # open file and search for all outgoing links
            with open(filename) as file:
                pre_mode = False
                for line in file:
                    if re.match("```",line) != None: # toggle preformatted mode
                        pre_mode = not pre_mode
                    if pre_mode: # skip preformatted mode
                        continue
                    while re.search("\{[^{}]+\}",line):
                        m = re.search("\{[^{}]+\}",line)
                        match = m.group() # matched string
                        if match not in incoming: # create a new set for that page
                            incoming[match] = set()
                        # add this file
                        incoming[match].add(wikilink)
                        line = line[m.end()+1:]

os.chdir('../tmp/')
# remove incoming links for:
# incoming.pop('{pages}')
incoming.pop('{home}')
#incoming.pop('{license}')

for key,links in incoming.items():
    # get filename for key
    filename = wikilink2Filename(key,'.gmo')
#    print(key)

    # open file in append mode
    with open(filename, 'a') as file:

        if len(links):
            # write incoming links
    #        print( '{} incoming links\n'.format( len(links) ) )
            file.write("\n\n# incoming links\n")
            for link in links:
                gemlink = '=> ./{} {}'.format(wikilink2Filename(link), link) 
                file.write(gemlink+"\n")
        else:
            print( '{}: orphan\n'.format(key) )
            file.write("\n\nno incoming links\n")
