import ast
import hashlib
import json
import os
from pathlib import Path
import sys

source = Path(sys.argv[1]).resolve()
smoke = source.parent / 'environment-smoke'
smoke.mkdir(exist_ok=True)
os.environ.update(OWL_HERTZ_SENTINEL='probe', SPT_HERTZ_SENTINEL='probe',
                  SPT_ATTACH_IPC_DEADLINE_MS='9', SPT_ATTACH_GATE_WATCHDOG_MS='9',
                  SPT_TEST_EPHEMERAL_ADVISORY_PORTS='9')
raw = source.read_bytes()
module = ast.parse(raw, filename=str(source))
boundary = next(i for i, node in enumerate(module.body)
                if isinstance(node, ast.Assign)
                and any(isinstance(target, ast.Name) and target.id == 'phases' for target in node.targets))
assert isinstance(module.body[boundary - 1], ast.FunctionDef)
assert module.body[boundary - 1].name == 'reap_owned'
prefix = ast.Module(body=module.body[:boundary], type_ignores=[])
namespace = {'__file__': str(source), '__name__': 'consumer_environment_probe'}
exec(compile(prefix, str(source), 'exec'), namespace)
namespace['PROOF'] = smoke
receipt = namespace['run']('golden-env-smoke', [sys.executable, str(smoke / 'consumer-env-probe.py')])
assert receipt['exit'] == 0, receipt
child = json.loads((smoke / 'golden-env-smoke.log').read_text())
assert child['proof'] == 'ENVIRONMENT_PROBE_NOT_A_TEST_RUN'
result = {'scope': 'actual driver configuration/functions and native child environment boundary; no consumer main, cargo, tests, claim, or reap executed',
          'driver_sha256': hashlib.sha256(raw).hexdigest(),
          'excluded_main_starts_at_line': module.body[boundary].lineno,
          'child': child, 'run_receipt': receipt}
(smoke / 'smoke-proof.json').write_text(json.dumps(result, indent=2) + '\n')
print('LINUX_ENVIRONMENT_SMOKE ' + json.dumps(result), flush=True)
