#!/usr/bin/env python3
#
# source: https://github.com/treyhunner/dotfiles/blob/main/bin/,md_urls

import re
from argparse import ArgumentParser
from collections import Counter, defaultdict
from pathlib import Path

OPEN_RE = re.compile(
    r"""
    \[ (?P<text> .+? ) \]
    \[ (?P<anchor> .*? ) \]
""",
    flags=re.VERBOSE,
)
CLOSE_RE = re.compile(
    r"""
    ^
    \[ (?P<anchor> .+? ) \]:
    \s+
    (?P<url> https?://.+ )
    $
""",
    flags=re.MULTILINE | re.VERBOSE,
)


def find_missing_anchors(markdown):
    start = [match["anchor"] or match["text"] for match in OPEN_RE.finditer(markdown)]
    end = [match["anchor"].lower() for match in CLOSE_RE.finditer(markdown)]
    return list({a: None for a in start if a.lower() not in end})


def get_all_anchored_links(markdown):
    return [
        (match["anchor"].lower(), match["url"]) for match in CLOSE_RE.finditer(markdown)
    ]


def main():
    parser = ArgumentParser()
    parser.add_argument("md_file", type=Path)
    parser.add_argument("--directory", type=Path, default=Path.cwd())
    args = parser.parse_args()
    missing_anchors = find_missing_anchors(args.md_file.read_text())
    anchors = defaultdict(Counter)
    for path in args.directory.rglob("*.md"):
        for anchor, url in get_all_anchored_links(path.read_text()):
            anchors[anchor][url] += 1
    for anchor in missing_anchors:
        if anchor.lower() not in anchors:
            url = ""
        else:
            [(url, _)] = anchors[anchor.lower()].most_common(1)
        print(f"[{anchor}]: {url}")


if __name__ == "__main__":
    main()
