import os
import os.path
import re

base = "https://arongranberg.com/astar/documentation"
for d in os.listdir("."):
    is_beta = "dev_" in d or "beta" in d
    if not os.path.isdir(d):
        continue

    branch = "beta" if is_beta else "stable"
    for p in os.listdir(d):
        if p.endswith(".html") or p.endswith(".php"):
            path = os.path.join(d, p)
            with open(path, "r") as f:
                text = f.read()
            pat = "\t<link rel=\"canonical\" href=\"[^\"]+?\">\n"
            count = len(re.findall(pat, text))
            if count > 1:
                print(f"replacing {count}")
                text = re.sub(pat, "", text, count=count-1)
                # text = text.replace("<head>", f"<head>\n\t<link rel=\"canonical\" href=\"{base}/{target}\">")
                with open(path, "w") as f:
                    f.write(text)
            # html_p = p.replace(".php", ".html").replace("class_", "").replace("pathfinding_1_1_", "").replace("-members", "")
            # targets = [f"{branch}/{html_p}", f"{branch}/{html_p.replace('-', '').replace('_','')}"]
            # target = next((target for target in targets if os.path.exists(target)), None)
            # if target is not None:
            #     print(f"Patching {path}: {target}")
            #     with open(path, "r") as f:
            #         text = f.read()
            #         text = text.replace("<head>", f"<head>\n\t<link rel=\"canonical\" href=\"{base}/{target}\">")
            #     with open(path, "w") as f:
            #         f.write(text)
            # else:
            #     print(f"Missing {d}: {targets[0]}")
