#!/usr/bin/env python3
"""Check every relative Markdown link under docs/: the target file exists and, where the link has a
fragment, an explicit <a id="..."></a> anchor with that name exists in the target file.

Run:  python3 docs/implementation_plan/tools/check_links.py [root]     (default root: docs/)
Exits non-zero if any link is broken or any anchor is defined twice in one file.
"""
import re, sys, os, glob, collections

ROOT = os.path.abspath(sys.argv[1] if len(sys.argv) > 1 else os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', '..'))
files = glob.glob(os.path.join(ROOT, '**', '*.md'), recursive=True)
anchors, dup = {}, []
for f in files:
    ids = re.findall(r'<a id="([^"]+)"></a>', open(f).read())
    dup += [(os.path.relpath(f, ROOT), i) for i, n in collections.Counter(ids).items() if n > 1]
    anchors[f] = set(ids)
bad, n = [], 0
for f in files:
    infence = False
    for ln, line in enumerate(open(f).read().split('\n'), 1):
        if line.lstrip().startswith('```'):
            infence = not infence
            continue
        if infence:
            continue
        for href in re.findall(r'\[[^\]\[]*\]\(([^)\s]+)\)', line):
            if re.match(r'[a-z]+://', href):
                continue
            n += 1
            path, _, frag = href.partition('#')
            tgt = os.path.normpath(os.path.join(os.path.dirname(f), path)) if path else f
            if not os.path.isfile(tgt):
                bad.append((os.path.relpath(f, ROOT), ln, href, 'missing file'))
            elif frag and tgt.endswith('.md') and frag not in anchors.get(tgt, ()):
                bad.append((os.path.relpath(f, ROOT), ln, href, 'missing anchor'))
print(f'markdown files: {len(files)}  links checked: {n}  broken: {len(bad)}  duplicate anchors: {len(dup)}')
for b in bad[:50]:
    print('  broken:', b)
for d in dup[:50]:
    print('  duplicate anchor:', d)
sys.exit(1 if bad or dup else 0)
