"""Tree-wide re-census: how many TOKEN-shaped shipping eprintln! sites sit BEHIND
a file's first module-opening #[cfg(test)] — i.e. inside the generator's blind spot.

Same predicate and containment logic as census.py, run over every tracked .rs file.
"""
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"


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 = subprocess.run(
    ["git", "ls-tree", "-r", "--name-only", SHA, "crates/"],
    capture_output=True, text=True, check=True, encoding="utf-8", errors="replace",
).stdout.split("\n")
files = [f for f in files if f.endswith(".rs")]

tot_ship = tot_blind = 0
rows = []
for f in files:
    blob = subprocess.run(["git", "show", f"{SHA}:{f}"], capture_output=True, text=True, encoding="utf-8", errors="replace")
    if blob.returncode:
        continue
    lines = blob.stdout.split("\n")
    ranges = test_ranges(lines)
    first_mod = ranges[0][0] if ranges else None
    ship = []
    for n, ln in enumerate(lines, 1):
        m = TOKEN.search(ln)
        if m and not any(a <= n <= b for a, b in ranges):
            ship.append((n, m.group(2)))
    if not ship:
        continue
    blind = [s for s in ship if first_mod and s[0] > first_mod]
    tot_ship += len(ship)
    tot_blind += len(blind)
    if blind:
        rows.append((len(blind), len(ship), first_mod, f))

nonblind = []
for f in files:
    blob = subprocess.run(["git", "show", f"{SHA}:{f}"], capture_output=True, text=True, encoding="utf-8", errors="replace")
    if blob.returncode:
        continue
    lines = blob.stdout.split("
")
    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 m and not any(a <= n <= b for a, b in ranges):
            if not (first_mod and n > first_mod):
                nonblind.append((f, n, m.group(1), m.group(2)))
print("
NOT in the blind spot (other mechanisms):", len(nonblind))
for f, n, tok, sep in nonblind:
    print(f"  {f}:{n}  {tok}{'(colon)' if sep==':' else '(space)'}")

rows.sort(reverse=True)
print(f"sha={SHA}  files with shipping TOKEN sites: counted")
print(f"TOTAL shipping TOKEN-shaped eprintln!: {tot_ship}")
print(f"  of which BEHIND the first module-opening cfg(test) (blind spot): {tot_blind}")
print("\nblind / total / first-cfg(test) / file")
for b, t, fm, f in rows[:25]:
    print(f"  {b:5d} / {t:5d} / {fm:6d} / {f}")
