"""Never-executed-in-CI cells for the #272 golden at fd296557.

Population: every test fn ADDED in git diff BASE..HEAD -- crates (a fn whose
preceding attribute lines carry #[test] / #[tokio::test] / #[...::test] at HEAD).
Executed-in: every preserved raw under .spt/preserved/ carrying a nextest PASS
line whose cell name ends in the fn name.
"""
import os, re, subprocess, sys, io
from collections import defaultdict

BASE, HEAD = "04e32c8c", "fd296557"
ROOT = os.getcwd()
PRES = os.path.join(ROOT, ".spt", "preserved")
OUT = os.path.join(PRES, "w3-fd296557", "NEVER-EXECUTED-CELLS.md")

def git(*a):
    return subprocess.run(["git", *a], capture_output=True, text=True, encoding="utf-8", errors="replace").stdout

# 1. added fn names per file from the diff
diff = git("diff", f"{BASE}..{HEAD}", "--", "crates")
added = defaultdict(set)  # file -> names
cur = None
for line in diff.splitlines():
    if line.startswith("+++ b/"):
        cur = line[6:]
    elif line.startswith("+") and not line.startswith("+++") and cur:
        m = re.match(r"\+\s*(?:pub(?:\([^)]*\))?\s+)?(?:async\s+)?fn\s+([A-Za-z_][A-Za-z0-9_]*)", line)
        if m:
            added[cur].add(m.group(1))

# 2. keep only fns that are tests at HEAD (attribute within 6 lines above the def)
ATTR = re.compile(r"#\[\s*(?:[\w:]+::)?test\b")
tests = defaultdict(list)  # file -> [name]
for f, names in sorted(added.items()):
    src = git("show", f"{HEAD}:{f}").splitlines()
    for i, l in enumerate(src):
        m = re.match(r"\s*(?:pub(?:\([^)]*\))?\s+)?(?:async\s+)?fn\s+([A-Za-z_][A-Za-z0-9_]*)", l)
        if not m or m.group(1) not in names:
            continue
        window = src[max(0, i - 6):i]
        if any(ATTR.search(w) for w in window if not w.lstrip().startswith("//")):
            if m.group(1) not in tests[f]:
                tests[f].append(m.group(1))

# 3. scan preserved raws for PASS lines
raws = []
for dp, dn, fn in os.walk(PRES):
    for x in fn:
        if x.endswith((".raw", ".log", ".txt")):
            raws.append(os.path.join(dp, x))
PASS = re.compile(r"\bPASS\s*\[[^\]]*\]\s+(?:\(\s*\d+/\d+\)\s+)?(\S+)(?:\s+(\S+))?\s*$")
seen = defaultdict(set)  # name -> set(relpath)
for p in raws:
    try:
        with open(p, "r", encoding="utf-8", errors="replace") as fh:
            for line in fh:
                m = PASS.search(line.rstrip("\r\n"))
                if not m:
                    continue
                cell = m.group(2) or m.group(1)
                leaf = cell.rsplit("::", 1)[-1]
                seen[leaf].add(os.path.relpath(p, PRES).replace("\\", "/"))
    except OSError:
        pass

# 4. write
total = 0; never = 0
o = io.StringIO()
o.write(f"# Never-executed-in-CI cells for the #272 golden at {HEAD}\n\n")
o.write(f"Population: every test fn ADDED in `git diff {BASE}..{HEAD} -- crates` "
        f"(last golden sha = v0.67.1 = {BASE}; a fn is a test if a `#[test]` / `#[tokio::test]`-shaped "
        f"attribute sits within 6 lines above its definition at {HEAD}). "
        "'Executed so far' = the preserved raws under `.spt/preserved/` carrying a nextest PASS line "
        "whose cell name ends in the fn name. None of these has run in CI: the last golden was v0.67.1 "
        "(docs-only), so EVERY cell below has its first CI execution at this golden.\n\n")
o.write(f"Scanned {len(raws)} preserved raw/log files.\n\n")
for f in sorted(tests):
    o.write(f"\n## {f}\n")
    for n in tests[f]:
        total += 1
        where = sorted(seen.get(n, ()))
        if where:
            o.write(f"- `{n}` -- executed in: {', '.join(where)}\n")
        else:
            never += 1
            o.write(f"- `{n}` -- **NO PASS line in any preserved raw** (rig-only cell or filtered out -- verify by name)\n")
ci_only = sorted(n for f in tests for n in tests[f] if any(w.endswith(".log") for w in seen.get(n, ())))
local_only = sorted(n for f in tests for n in tests[f] if n not in ci_only)
o.write(f"\n**Totals:** {total} test cells added {BASE}..{HEAD}; {total - never} carry a preserved PASS line; "
        f"{never} carry none.\n")
o.write(f"\n**Already executed in a thin-CI GitHub job (a preserved `.log`):** {len(ci_only)}.\n")
o.write(f"\n**Executed ONLY in local gate batteries / rigs (never in any GitHub job):** {len(local_only)}\n")
for n in local_only:
    o.write(f"- `{n}`\n")
with open(OUT, "w", encoding="utf-8", newline="\n") as fh:
    fh.write(o.getvalue())
print(f"wrote {OUT}: total={total} passed_somewhere={total-never} none={never} raws={len(raws)}")
