import os
import sys
import re
import posixpath
import argparse

linkre = re.compile(r"\[(.+?)\]\((.+?)\)")

def normlink(link,start_link):
    if link.startswith("http"):
        return link
    target = posixpath.normpath(link)
    # Absolute path
    if target[0] == "/":
        return target
    elif target.startswith("./"):
        target = posixpath.normpath(start_link +  target)
    else:
        target = posixpath.normpath(start_link +  "/" + target)
    #print(">>>>>>" + link + " " + target)
    #print(target)
    return target

def process(lfrom,lto):
    for root, dirs, files in os.walk("./pages", topdown=False):
        for file_name in files:
            if not file_name.endswith(".md"):
                continue
            full_file_name = root + "/"+ file_name
            # strip README.md
            page_name = full_file_name[7:-10]
            #print(page_name)
            def replink(match):
                name = match.group(1)
                target = normlink(match.group(2),page_name)
                #print(lto)
                #print(target)
                out = match.group(0)
                if target == lfrom:
                    print("match at" + page_name + ":" + name)
                    if lto:
                        out = "[{}]({})".format(name,lto)
                        #print("Replaced to " + out) 

                return out

            content = []
            changed = False
            with open(full_file_name) as f:
                for l in f:
                    if re.search(linkre,l) is not None:
                        line = re.sub(linkre,replink,l)
                        if line != l:
                            print("replace")
                            print(l.rstrip())
                            print(line.rstrip())
                            answer = sys.stdin.readline().strip()
                            if len(answer) == 0 or answer[0] != "n":
                                l = line
                                changed = True
                    content.append(l)
            if lto and changed:
                with open(full_file_name,"w") as f:
                    f.write("".join(content))

if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("lfrom")
    parser.add_argument("-r","--replace",type=str)
    args = parser.parse_args()
    process(args.lfrom,args.replace)

