import io

p = ".github/ci/ws272-w2.py"
s = io.open(p, encoding="utf-8").read()


def sub(old, new):
    global s
    assert s.count(old) == 1, (s.count(old), old[:70])
    s = s.replace(old, new, 1)


# 1. The missing binary. `kind(test)` targets enter ONLY by name, so the rig
#    carrying the F1 conjuncts was outside the selection while the floor passed.
sub(
    'W2_TEST_BINS = ("webserve_attachment_e2e",)',
    '''# Integration binaries are kind(test) and enter ONLY by name — a lesson the
# gater caught before this ran blind: `webserve_cross_node_e2e` carries the F1
# authorization conjuncts and the FILE_ACCESS_HELPER int arm, and without it
# named here the battery would have passed the floor while skipping the two
# things the gate most wants to read.
W2_TEST_BINS = ("webserve_attachment_e2e", "webserve_cross_node_e2e")''',
)

# 2. The counter. Measured against a real listing: this nextest prints
#    "<package> <test::path>" lines and NONE of the summary phrases the old
#    regexes looked for, so it counted indented lines instead — of which there
#    is exactly one — and refused a selection of 1673.
sub(
    '''    raw = (output / "population.raw").read_text(encoding="utf-8", errors="replace")
    match = re.search(r"(\\d+) tests? across", raw) or re.search(r"(\\d+) binaries", raw)
    count = sum(1 for line in raw.splitlines() if line.startswith("    "))
    selected = int(match.group(1)) if match and "tests" in match.group(0) else count''',
    '''    raw = (output / "population.raw").read_text(encoding="utf-8", errors="replace")
    # COUNT THE ROWS THEMSELVES, never a summary phrase: `nextest list` prints
    # one "<package> <test::path>" line per selected test and no total, so a
    # meter keyed on prose reads zero and refuses a healthy battery. Measured
    # against a real listing (1673 selected) after the first version did exactly
    # that — the instrument was wrong, not the filter.
    selected = sum(1 for line in raw.splitlines() if re.match(r"^\\S+ \\S*::", line))''',
)

io.open(p, "w", encoding="utf-8", newline="").write(s)
print("driver fixed")
