"""Triage vulture findings: count references to each flagged name outside its definition line."""
import re, subprocess, sys, pathlib

def refs(repo, name, def_file, def_line):
    # count occurrences of the name as a word in .py files, excluding the def line itself
    out = subprocess.run(["grep", "-rn", "--include=*.py", "-w", name, ".", "--exclude-dir=.venv", "--exclude-dir=data"],
                         cwd=repo, capture_output=True, text=True).stdout.splitlines()
    others = [l for l in out if not (l.startswith(f"{def_file}:{def_line}:") or l.startswith(f"./{def_file}:{def_line}:"))]
    return others

for path in sys.argv[1:]:
    print(f"### {path}")
    for line in open(path):
        m = re.match(r"(.+):(\d+): unused (?:function|method|variable|attribute|property|class|import) '([^']+)'", line.strip())
        if not m: continue
        f, ln, name = m.group(1), int(m.group(2)), m.group(3)
        repo = "/home/hatch/workspace/retriever-doc-answer" if "retriever" in path else "/home/hatch/workspace/jokeGPT"
        others = refs(repo, name, f, ln)
        print(f"{f}:{ln} {name}: {len(others)} other refs")
        for o in others[:3]:
            print(f"    {o[:140]}")
