import os
import re

TARGET_DIR = "src/content/docs/szmgr"

footnote_pattern = re.compile(r"\[([a-zA-Z0-9_-]+)\]\(#[a-zA-Z0-9_-]+\)")
explanation_pattern = re.compile(r"- \[\[\[([\w+-]+).+\]\]\]")

files = [f for f in os.listdir(TARGET_DIR) if f.endswith(".md")]

for f in files:
    print(f"\t- {f}")
    lines = []
    with open(os.path.join(TARGET_DIR, f), "r") as file:
        lines = file.readlines()
    
    for i in range(len(lines)):
        l = lines[i]

        matches = list(footnote_pattern.finditer(l))
        if matches:
            # Reverse so replacements don't mess up span positions
            for match in reversed(matches):
                topic = match.group(1)
                start, end = match.span()
                l = l[:start] + f"[^{topic}]" + l[end:]
            
            lines[i] = l
            
        m = explanation_pattern.match(l + "\n")
        if m:
            topic = m.group(1)
            start, end = m.span()
            l = l[:start] + f"[^{topic}]:" + l[end:]
            lines[i] = l

        if "## Zdroje" in l:
            lines[i] = ""
    
    with open(os.path.join(TARGET_DIR, f), "w") as file:
        file.writelines(lines)
