"""Which census rows are NOT emissions at all?

The census attributes a macro by scanning up to 4 lines back from the token
literal. That window can reach an `eprintln!` that the literal does not belong
to: sealverb.rs:456 is `format!("SEAL_SEND_NO_DAEMON: ...")` inside a `map_err`,
three lines below an unrelated `eprintln!`, and the census counted it as an
emission of that macro.

This re-checks every row by BALANCED-PAREN CONTAINMENT: is the token literal's
line actually inside the macro call's span? Rows that are not are phantoms.
"""
import re
import subprocess
import sys

SHA = sys.argv[1] if len(sys.argv) > 1 else "4d6007ac"
SITES = r"C:/Users/decid/AppData/Local/Temp/claude/C--Users-decid-Documents-projects-spt-core/43af483b-6d22-46cb-9d99-8b7713a6ff46/scratchpad/cut-4d6007ac/census_sites.txt"
MACRO = re.compile(r"\b(eprintln!|println!|eprint!|print!)")
MACRO_OPEN = re.compile(r"\b(eprintln!|println!|eprint!|print!)\s*\(")

cache = {}
def blob(p):
    if p not in cache:
        cache[p] = subprocess.run(
            ["git", "show", f"{SHA}:{p}"], capture_output=True, check=True
        ).stdout.decode("utf-8", "replace").split("\n")
    return cache[p]

def call_span_lines(lines, start):
    """(first_line, last_line) of the macro call opening at/after `start`."""
    text = "\n".join(lines[start:start + 80])
    m = MACRO_OPEN.search(text)
    if not m:
        return None
    i = m.end() - 1
    depth = 0
    instr = False
    esc = False
    for k in range(i, len(text)):
        c = text[k]
        if instr:
            if esc:
                esc = False
            elif c == chr(92):
                esc = True
            elif c == '"':
                instr = False
            continue
        if c == '"':
            instr = True
        elif c == "(":
            depth += 1
        elif c == ")":
            depth -= 1
            if depth == 0:
                return (start, start + text[:k].count("\n"))
    return None

rows = [l.split("\t") for l in open(SITES, encoding="utf-8").read().splitlines()]
phantoms = []
for loc, tok, mac in rows:
    path, ln = loc.rsplit(":", 1)
    lines = blob(path)
    j = int(ln) - 1
    start = None
    for k in range(j, max(-1, j - 5), -1):
        if MACRO.search(lines[k]):
            start = k
            break
    if start is None:
        phantoms.append((loc, tok, mac, "no macro found"))
        continue
    span = call_span_lines(lines, start)
    if span is None:
        phantoms.append((loc, tok, mac, "unclosed call"))
        continue
    lo, hi = span
    if not (lo <= j <= hi):
        phantoms.append((loc, tok, mac, f"literal outside the call span {lo+1}-{hi+1}"))

print(f"census rows: {len(rows)}   PHANTOMS (not emissions): {len(phantoms)}")
for loc, tok, mac, why in phantoms:
    path, ln = loc.rsplit(":", 1)
    src = blob(path)[int(ln) - 1].strip()
    print(f"  {loc}\t{tok}\t{why}\n      {src[:100]}")
