"""QKJ45BRT: four non-interleaved arms using the already-proved cohort driver."""
import json
import os
from pathlib import Path
import subprocess
import sys

HERE = Path(__file__).resolve().parent
ROOT = HERE.parents[2]
DRIVER = HERE / 'cohort-driver.py'
AUTHORITY = HERE / 'authority-QKJ45BRT.json'
PROOF = HERE / 'native-proof-journal-prove-receipt.json'
ROOTS = json.loads((HERE / 'participating-target-roots.json').read_text())['roots']
ENV = {k: v for k, v in os.environ.items() if not k.upper().startswith(('OWL_', 'SPT_', 'NEXTEST_'))}
KNOWN = '52860=liam elevated perch, prior doyle W8TQ3MZC via S2-window6-pre-GO-receipt.json, same PID/ppid/birth in known-unreadable-52860.json'


def execute(label, argv, acceptable=(0,)):
    with (HERE / (label + '-outer.log')).open('xb') as log:
        result = subprocess.run(argv, cwd=ROOT, env=ENV, stdin=subprocess.DEVNULL,
                                stdout=log, stderr=subprocess.STDOUT)
    with (HERE / (label + '-outer-exit.json')).open('x') as out:
        json.dump({'argv': argv, 'exit': result.returncode}, out, indent=2)
    print(json.dumps({'stage': label, 'exit': result.returncode}), flush=True)
    if result.returncode not in acceptable:
        raise SystemExit(result.returncode or 125)


def admission(label):
    tag = 'QKJ45BRT-' + label
    execute(tag, ['pwsh', '-NoProfile', '-File', str(HERE / 'admit-cohort.ps1'),
                  '-Tag', tag, '-Roots', ';'.join(ROOTS), '-AuthorityFile', str(AUTHORITY),
                  '-KnownUnreadable', KNOWN])
    return HERE / (tag + '-receipt.json')


for selector, arm in [('g1', 'golden'), ('g7', 'consumer'), ('g7', 'golden')]:
    label = selector + '-' + arm
    listed = label + '-list'
    admitted = admission(listed + '-admission')
    common = ['--authority', str(AUTHORITY), '--proof', str(PROOF),
              '--selector', selector, '--arm', arm]
    execute(listed, [sys.executable, str(DRIVER), 'list', '--admission', str(admitted),
                     '--label', listed] + common)
    admitted = admission(label + '-admission')
    execute(label, [sys.executable, str(DRIVER), 'cohort', '--admission', str(admitted),
                    '--label', label, '--inventory', str(HERE / (listed + '-list-receipt.json'))]
                   + common, (0, 100))
    receipt = json.loads((HERE / (label + '-cohort-receipt.json')).read_text())
    assert receipt['verdict'] == 'COHORT_COMPLETE' and len(receipt['results']) == 10
    print(json.dumps({'arm': label, 'passed': sum(r['native_exit'] == 0 for r in receipt['results']),
                      'failed': sum(r['native_exit'] == 100 for r in receipt['results'])}), flush=True)
