"""W9 negative control: put serving back in the BROKER (base placement).
apply   -> daemon.rs = base blob (1aecaa95) in CRLF, brain bring-up disabled.
restore -> original bytes back, sha256 asserted equal to the pre-apply capture."""
import hashlib, json, os, subprocess, sys

ROOT = os.getcwd()
FILES = ['crates/spt-daemon/src/daemon.rs', 'crates/spt-daemon/src/brainproc.rs']
STATE = os.path.join(os.path.dirname(__file__), 'mut-state.json')
BACKUP = os.path.join(os.path.dirname(__file__), 'mut-backup')


def sha(b):
    return hashlib.sha256(b).hexdigest()


def apply():
    if os.path.exists(STATE):
        sys.exit('already applied')
    os.makedirs(BACKUP, exist_ok=True)
    state = {}
    for f in FILES:
        raw = open(f, 'rb').read()
        state[f] = sha(raw)
        open(os.path.join(BACKUP, os.path.basename(f)), 'wb').write(raw)
    base = subprocess.check_output(['git', 'show', '1aecaa95:crates/spt-daemon/src/daemon.rs'])
    base = base.replace(b'\r\n', b'\n').replace(b'\n', b'\r\n')
    open(FILES[0], 'wb').write(base)
    bp = open(FILES[1], 'rb').read()
    old = b'if let Some(port) = crate::docshost::start_daemon_serving(name.clone()) {'
    assert bp.count(old) == 1, 'brain bring-up anchor'
    bp = bp.replace(old, b'if let Some(port) = { let _ = &name; None::<u16> } {')
    open(FILES[1], 'wb').write(bp)
    json.dump(state, open(STATE, 'w'))
    print('MUTANT APPLIED', state)


def restore():
    state = json.load(open(STATE))
    for f in FILES:
        raw = open(os.path.join(BACKUP, os.path.basename(f)), 'rb').read()
        open(f, 'wb').write(raw)
        got = sha(open(f, 'rb').read())
        assert got == state[f], f'{f}: {got} != {state[f]}'
    os.remove(STATE)
    print('RESTORED, sha256 match', state)


{'apply': apply, 'restore': restore}[sys.argv[1]]()
