"""Independent re-census meter (todlando, reconciling doyle's IR-69 close-out finding).

Predicate: an `eprintln!` whose format literal STARTS with an UPPERCASE token
(A-Z, 0-9, _) followed by `:` or a space. Classification is by cfg(test)-module
CONTAINMENT, brace-tracked, not by line grep.

Deliberately written from the description rather than from doyle's script, so the
two meters are independent: agreement is then evidence, not a shared bug.
"""
import re
import sys

path = sys.argv[1]
src = open(path, encoding="utf-8").read()
lines = src.split("\n")

# --- brace-tracked cfg(test) module ranges -------------------------------
# A cfg(test) attribute followed (possibly after other attrs) by a `mod X {`.
test_ranges = []
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 = 0
            started = False
            k = 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
            test_ranges.append((i + 1, k + 1))  # 1-indexed inclusive
            i = k + 1
            continue
    i += 1


def in_test(lineno):
    return any(a <= lineno <= b for a, b in test_ranges)


TOKEN = re.compile(r'eprintln!\(\s*"([A-Z][A-Z0-9_]*)(:| )')

ship, test = [], []
for n, ln in enumerate(lines, 1):
    m = TOKEN.search(ln)
    if m:
        (test if in_test(n) else ship).append((n, m.group(1), m.group(2)))

print(f"file={path} lines={len(lines)}")
print(f"cfg(test) module ranges: {len(test_ranges)} -> {test_ranges[:8]}")
print(f"TOKEN-shaped eprintln!: shipping={len(ship)} in-test={len(test)}")
if ship:
    print(f"  first shipping site: line {ship[0][0]} token {ship[0][1]!r}")
    print(f"  last  shipping site: line {ship[-1][0]} token {ship[-1][1]!r}")
    before = [s for s in ship if s[0] < 3007]
    after = [s for s in ship if s[0] > 3164]
    print(f"  shipping sites BEFORE line 3007: {len(before)}")
    print(f"  shipping sites AFTER  line 3164: {len(after)}")
    colon = [s for s in ship if s[2] == ":"]
    space = [s for s in ship if s[2] == " "]
    print(f"  by separator: colon={len(colon)} space={len(space)}")
