"""Check every fenced code line in the blog drafts against a source tree.

usage: python -I check_excerpts.py <tree> <md>...

Each code line is whitespace-normalised and looked up among the tree's normalised lines.
A miss is retried with a trailing // or # comment removed, so an annotation the post added
is reported separately from code that is not in the source at all.
"""
import pathlib
import re
import sys

sys.stdout.reconfigure(encoding="utf-8")
tree = pathlib.Path(sys.argv[1])
norm = lambda s: re.sub(r"\s+", " ", s).strip()
src_lines = {}
for p in tree.rglob("*"):
    if p.is_file() and p.suffix in {".cpp", ".h", ".txt", ".rc", ".desktop", ""} or p.name == ".clangd":
        try:
            for ln in p.read_text(encoding="utf-8").splitlines():
                n = norm(ln)
                if n:
                    src_lines.setdefault(n, set()).add(str(p.relative_to(tree)))
        except (UnicodeDecodeError, IsADirectoryError):
            pass
corpus = "\n".join(src_lines)

def found(n):
    if n in src_lines:
        return True
    # a line the post joined or split: accept it as a substring of one source line
    return len(n) > 12 and n in corpus

for md in sys.argv[2:]:
    text = pathlib.Path(md).read_text(encoding="utf-8")
    print(f"=== {pathlib.Path(md).name}")
    in_code = False
    for i, line in enumerate(text.splitlines(), 1):
        if line.lstrip().startswith("```"):
            in_code = not in_code
            continue
        if not in_code:
            continue
        n = norm(line)
        if not n or "..." in n or "…" in n or n in {"{", "}", "};", "break;", "}}"}:
            continue
        if found(n):
            continue
        code = norm(re.split(r"\s(//|#)\s", line)[0])
        if code and found(code):
            print(f"  {i:4} COMMENT  {n}")
        else:
            print(f"  {i:4} MISSING  {n}")
