"""Tree-wide re-census at a sha: TOKEN-shaped shipping eprintln! sites, split by
whether they sit BEHIND the file's first module-opening #[cfg(test)] (the census
generator's blind spot) or not (some other mechanism).
"""
import re
import subprocess
import sys

TOKEN = re.compile(r'eprintln!\(\s*"([A-Z][A-Z0-9_]*)(:| )')
SHA = sys.argv[1] if len(sys.argv) > 1 else "origin/main"
NL = chr(10)


def run(args):
    return subprocess.run(
        args, capture_output=True, text=True, encoding="utf-8", errors="replace"
    )


def test_ranges(lines):
    out, i = [], 0
    while i < len(lines):
        if lines[i].strip() == "#[cfg(test)]":
            j = i + 1
            while j < len(lines) and (lines[j].strip().startswith("#[") or not lines[j].strip()):
                j += 1
            if j < len(lines) and re.match(r"\s*(pub\s+)?mod\s+\w+", lines[j]):
                depth, started, k = 0, False, j
                while k < len(lines):
                    depth += lines[k].count("{") - lines[k].count("}")
                    if "{" in lines[k]:
                        started = True
                    if started and depth <= 0:
                        break
                    k += 1
                out.append((i + 1, k + 1))
                i = k + 1
                continue
        i += 1
    return out


files = [
    f for f in run(["git", "ls-tree", "-r", "--name-only", SHA, "crates/"]).stdout.split(NL)
    if f.endswith(".rs")
]

blind, other = [], []
for f in files:
    blob = run(["git", "show", SHA + ":" + f])
    if blob.returncode:
        continue
    lines = blob.stdout.split(NL)
    ranges = test_ranges(lines)
    first_mod = ranges[0][0] if ranges else None
    for n, ln in enumerate(lines, 1):
        m = TOKEN.search(ln)
        if not m or any(a <= n <= b for a, b in ranges):
            continue
        rec = (f, n, m.group(1), m.group(2))
        (blind if (first_mod and n > first_mod) else other).append(rec)

print("sha=" + SHA)
print("TOTAL shipping TOKEN-shaped eprintln!: " + str(len(blind) + len(other)))
print("  behind first module-opening cfg(test) (BLIND SPOT): " + str(len(blind)))
print("  not in the blind spot (OTHER mechanism): " + str(len(other)))

by_file = {}
for f, n, tok, sep in blind:
    by_file[f] = by_file.get(f, 0) + 1
print(NL + "blind-spot files:")
for f, c in sorted(by_file.items(), key=lambda kv: -kv[1]):
    print("  " + str(c).rjust(5) + "  " + f)

print(NL + "NOT in the blind spot — enumerate, these need individual provenance:")
for f, n, tok, sep in other:
    print("  " + f + ":" + str(n) + "  " + tok + ("(colon)" if sep == ":" else "(space)"))
