from pathlib import Path
import os
os.chdir(r"C:\Users\decid\Documents\projects\spt-core\.worktrees\ws272-w0")
p = Path(".github/ci/ws272-w0.py")
s = p.read_bytes().decode("utf-8").replace("\r\n", "\n")

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

swap('''    path = Path(root) / ".spt" / "driver.lock"
    path.parent.mkdir(parents=True, exist_ok=True)
    handle = open(path, "a+", encoding="utf-8")''',
'''    path = Path(root) / ".spt" / "driver.lock"
    path.parent.mkdir(parents=True, exist_ok=True)
    # The holder pid lives in a sibling note: Windows denies reads of a byte
    # another process holds locked, so the lock file itself cannot say who.
    holder_note = path.with_suffix(".holder")
    handle = open(path, "a+", encoding="utf-8")''')

swap('''    except OSError:
        handle.seek(0)
        holder = handle.read().strip() or "unknown"
        handle.close()
        print(f"POOL_HELD:''',
'''    except OSError:
        handle.close()
        try:
            holder = holder_note.read_text(encoding="utf-8").strip() or "unknown"
        except OSError:
            holder = "unknown"
        print(f"POOL_HELD:''')

# the write-pid-into-lock block: slice by anchors, no backslashes in the match
start = s.index("    handle.seek(0)\n    handle.truncate()\n    handle.write(")
end = s.index("    return handle\n", start)
s = s[:start] + '    holder_note.write_text(str(os.getpid()) + "\\n", encoding="utf-8")\n' + s[end:]

swap('''        first = claim_pool(Path(tmp))
        if first is None:
            raise AssertionError("lane lock: first claim refused")
        probe = [sys.executable, str(Path(__file__).resolve()), "--probe-lock", tmp]
        held = subprocess.run(probe, capture_output=True, text=True)
        if held.returncode != 4 or "POOL_HELD" not in held.stdout:
            raise AssertionError(f"lane lock: second driver not refused: rc={held.returncode} "
                                 f"out={held.stdout!r} err={held.stderr!r}")
        first.close()''',
'''        first = claim_pool(Path(tmp))
        if first is None:
            raise AssertionError("lane lock: first claim refused")
        probe = [sys.executable, str(Path(__file__).resolve()), "--probe-lock", tmp]
        try:
            held = subprocess.run(probe, capture_output=True, text=True)
        finally:
            first.close()
        if held.returncode != 4 or f"pid {os.getpid()}" not in held.stdout:
            raise AssertionError(f"lane lock: second driver not refused naming the holder: rc={held.returncode} "
                                 f"out={held.stdout!r} err={held.stderr!r}")''')

assert "handle.write(" not in s and s.count("holder_note") == 3
p.write_bytes(s.replace("\n", "\r\n").encode("utf-8"))
print("patched: holder note + finally-close")
