#!/usr/bin/env python3
# todo - find TODO/FIXME/XXX comments in a tree, with counts by file
# Usage: todo [DIR] [--pattern TODO|FIXME|XXX] [--ext .py,.c] [--ignore DIR]
import argparse, collections, os, re, sys

DEFAULT_PAT = re.compile(r"\b(TODO|FIXME|XXX|HACK)\b\s*:?\s*(.*)", re.IGNORECASE)
SKIP_DIRS = {".git", "__pycache__", ".venv", "venv", "node_modules", ".hg", "target", "build"}
SKIP_EXTS = {".pyc", ".o", ".so", ".png", ".jpg", ".gif", ".zip", ".gz", ".pdf"}

def selftest():
    import tempfile
    with tempfile.TemporaryDirectory() as d:
        open(os.path.join(d, "a.py"), "w").write("# TODO: fix this\nx = 1  # FIXME: hacky\n# nothing\n")
        open(os.path.join(d, "b.c"), "w").write("// XXX: revisit\n/* TODO: later */\n")
        out = subprocess.run([sys.executable, os.path.abspath(__file__), d],
                             capture_output=True, text=True)
        assert out.returncode == 0, out.stderr
        assert "4 marker(s)" in out.stdout, out.stdout
        assert "a.py" in out.stdout and "b.c" in out.stdout
        print("todo selftest: PASS")
    return 0

import subprocess

def main():
    ap = argparse.ArgumentParser(prog="todo",
        description="Find TODO/FIXME/XXX comments in a tree, with counts by file.")
    ap.add_argument("dir", nargs="?", default=".", help="directory to scan (default: .)")
    ap.add_argument("--pattern", default="TODO|FIXME|XXX|HACK",
                    help="tag pattern (default TODO|FIXME|XXX|HACK)")
    ap.add_argument("--ext", help="only these extensions, comma-separated (e.g. .py,.c)")
    ap.add_argument("--ignore", action="append", default=[], help="extra directory to skip")
    ap.add_argument("--selftest", action="store_true", help="run built-in self-test and exit")
    a = ap.parse_args()
    if a.selftest:
        return selftest()
    try:
        pat = re.compile(r"\b(%s)\b\s*:?\s*(.*)" % a.pattern, re.IGNORECASE)
    except re.error as e:
        print("todo: bad pattern: %s" % e, file=sys.stderr); return 2
    exts = set(e if e.startswith(".") else "." + e for e in a.ext.split(",")) if a.ext else None
    skip = SKIP_DIRS | set(a.ignore)
    per_file = collections.Counter()
    per_tag = collections.Counter()
    hits = []
    for root, dirs, names in os.walk(a.dir):
        dirs[:] = [d for d in dirs if d not in skip]
        for n in names:
            p = os.path.join(root, n)
            if os.path.splitext(n)[1] in SKIP_EXTS:
                continue
            if exts and os.path.splitext(n)[1] not in exts:
                continue
            try:
                with open(p, errors="replace") as f:
                    for ln, line in enumerate(f, 1):
                        m = pat.search(line)
                        if m:
                            tag = m.group(1).upper()
                            per_file[p] += 1
                            per_tag[tag] += 1
                            hits.append((p, ln, tag, m.group(2).strip()[:100]))
            except (OSError, UnicodeError):
                continue
    total = sum(per_file.values())
    print("todo: %d marker(s) in %d file(s)" % (total, len(per_file)))
    for tag, n in per_tag.most_common():
        print("  %s: %d" % (tag, n))
    print("by file:")
    for p, n in per_file.most_common():
        print("  %4d  %s" % (n, p))
    for p, ln, tag, text in hits:
        print("  %s:%d [%s] %s" % (p, ln, tag, text))
    return 0

if __name__ == "__main__":
    sys.exit(main())
