import io, os, subprocess, sys

REPO = r"C:\Users\decid\Documents\projects\spt-core"
BASE = "c4109a5819084aa3f8daf5247ea7cf30baaf6539"   # de5a44bc + hertz instrumentation
HEAD_ARM = "1bd0a41d67c0389bea3879bbf18b56763ba0dc1e"  # a9e786b2 + instr + retention


def git(*args, binary=False, **kw):
    r = subprocess.run(["git", "-C", REPO, *args], capture_output=True, **kw)
    if r.returncode != 0:
        sys.exit("git %s failed: %s" % (args[0], r.stderr.decode('utf-8', 'replace')))
    return r.stdout if binary else r.stdout.decode('utf-8').strip()


# 1. base's OWN nextest.toml (blob layer -> LF), not a copy of head's.
blob = git("show", "%s:.config/nextest.toml" % BASE, binary=True)
print("base nextest.toml:", len(blob), "bytes, CR", blob.count(b"\r"))
EOL = b"\r\n" if blob.count(b"\r\n") else b"\n"

note = EOL.join([
    b"# DIAGNOSTIC-BRANCH ONLY (releases#294 poll-margin comparison). nextest's default",
    b"# success-output is `never`, which SUPPRESSES the IR95 instrumentation lines on exactly",
    b"# the path a passing cell takes -- the run would then answer pass/fail and yield NO",
    b"# margins, which is the whole point of the comparison. Set on BOTH platform profiles so",
    b"# the two arms differ in nothing but their tree. NOT for main.",
    b'success-output = "immediate"',
]) + EOL

a1 = b'slow-timeout = { period = "60s", terminate-after = 4 }' + EOL
a2 = b'test-threads = 8' + EOL
assert blob.count(a1) == 1, ("default anchor", blob.count(a1))
assert blob.count(a2) == 1, ("ci-windows anchor", blob.count(a2))
new_blob = blob.replace(a1, a1 + note, 1).replace(a2, a2 + note, 1)
assert new_blob.count(b'success-output = "immediate"') == 2

# 2. write blob, build tree from BASE with that one path replaced, commit.
p = os.path.join(os.environ.get("TEMP", "."), "base_nextest.toml")
io.open(p, "wb").write(new_blob)
blob_sha = git("hash-object", "-w", "--", p)
print("new blob:", blob_sha)

idx = os.path.join(os.environ.get("TEMP", "."), "base_arm.index")
if os.path.exists(idx):
    os.remove(idx)
env = dict(os.environ, GIT_INDEX_FILE=idx)
git("read-tree", BASE, env=env)
git("update-index", "--add", "--cacheinfo", "100644,%s,.config/nextest.toml" % blob_sha, env=env)
tree = git("write-tree", env=env)
print("new tree:", tree)

msg = (
    "test(diag): retain passing-test output so poll margins survive a PASS\n\n"
    "Base arm of the releases#294 poll-margin comparison. Identical retention\n"
    "change to the head arm (1bd0a41d), applied to THIS tree's own nextest.toml\n"
    "rather than copied -- the two baselines' configs already differ by one line.\n\n"
    "Diagnostic branch only. Not for main.\n\n"
    "Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>\n"
    "Claude-Session: https://claude.ai/code/session_01R1dpz1xXZdTeyjGeKDSbNW\n"
)
mp = os.path.join(os.environ.get("TEMP", "."), "base_arm_msg.txt")
io.open(mp, "w", encoding="utf-8", newline="\n").write(msg)
commit = git("commit-tree", tree, "-p", BASE, "-F", mp)
print("base arm commit:", commit)

# 3. THE VERIFICATION: the two arms' configs must differ ONLY by the pre-existing line.
d = git("diff", "%s:.config/nextest.toml" % commit, "%s:.config/nextest.toml" % HEAD_ARM)
added = [l for l in d.splitlines() if l.startswith('+') and not l.startswith('+++')]
removed = [l for l in d.splitlines() if l.startswith('-') and not l.startswith('---')]
print("\nconfig diff base-arm vs head-arm: +%d / -%d line(s)" % (len(added), len(removed)))
for l in added + removed:
    print("   ", l[:110])
print("\nretention lines present in base arm:",
      git("show", "%s:.config/nextest.toml" % commit).count('success-output = "immediate"'))
