"""ORDER negative control: the adapters leg no longer waits for promotion.
usage: mutate_order.py apply|restore  (restore asserts byte identity)"""
import hashlib, shutil, sys, os
F = 'crates/spt-daemon/src/autoapply.rs'
BK = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'order-backup.rs')
SHA = BK + '.sha'
OLD = '''    let Some(AppliedRecord::Applied { version }) = applied else {
        return None;
    };
    let v = staged_version.filter(|s| s == version)?;'''
NEW = '''    let _ = applied; // NEGATIVE CONTROL: the leg runs pre-promotion
    let v = staged_version?;'''
sha = lambda p: hashlib.sha256(open(p, 'rb').read()).hexdigest()
if sys.argv[1] == 'apply':
    shutil.copy2(F, BK); open(SHA, 'w').write(sha(F))
    s = open(F, encoding='utf-8').read(); assert s.count(OLD) == 1
    open(F, 'w', encoding='utf-8', newline='\n').write(s.replace(OLD, NEW)); print('mutated')
else:
    shutil.copy2(BK, F); assert sha(F) == open(SHA).read().strip(); print('restored byte-identical')
