"""Verify native observation without issuing control, trade, navigation or OS input."""
import argparse, json, pathlib, subprocess, sys, time

p = argparse.ArgumentParser()
p.add_argument('--pid', type=int, required=True)
p.add_argument('--image', required=True)
p.add_argument('--output', type=pathlib.Path, required=True)
args = p.parse_args()
host = pathlib.Path(__file__).resolve().parents[1] / 'XFEEDToolBox' / 'Bridge' / 'native-host.py'
process = subprocess.Popen([sys.executable, '-u', str(host), '--pid', str(args.pid), '--image', args.image, '--sha256', 'e6be8bbe04e6a7ae226d4318945af7f367de13dc5a007a261964d9ba8144e988'], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, encoding='utf-8')
report = {'nativeObservationValidated': False, 'mutatingCommandsIssued': 0}
try:
    for i, method in enumerate(['describe', 'native.state']):
        if i: time.sleep(1.5)
        process.stdin.write(json.dumps({'id': str(i), 'method': method}) + '\n'); process.stdin.flush()
        line = process.stdout.readline()
        if not line: raise RuntimeError(process.stderr.read(1000))
        response = json.loads(line)
        if not response.get('ok'): raise RuntimeError(response.get('error'))
        report[method] = response['result']
    report['nativeObservationValidated'] = bool(report['native.state'].get('observedAt'))
finally:
    process.stdin.close()
    try: process.wait(timeout=5)
    except subprocess.TimeoutExpired: process.kill();process.wait()
    args.output.parent.mkdir(parents=True, exist_ok=True)
    args.output.write_text(json.dumps(report, ensure_ascii=False, indent=2), encoding='utf-8')
print(json.dumps(report, ensure_ascii=False, indent=2))
if not report['nativeObservationValidated']: sys.exit(1)
