"""Six Linux execution-context fixtures; no cron, existing job or network access.

Python 3.9+ standard library. Writes only a new, uniquely named child directory.
Each child shell gets a deliberately constructed allowlist environment.
"""
import argparse
import datetime
import json
import os
import platform
import shlex
import subprocess
import time
import uuid
from pathlib import Path


WORKER = '''#!/bin/sh
LLAB_INPUT=${1:-./payload.txt}
if [ ! -r "$LLAB_INPUT" ]; then
    printf '%s\\n' 'input_missing' >&2
    exit 20
fi
IFS= read -r LLAB_PAYLOAD < "$LLAB_INPUT"
if [ "${LLAB_JOB_LABEL:-}" != demo ]; then
    printf '%s\\n' 'label_missing' >&2
    exit 21
fi
if [ "$LLAB_PAYLOAD" != synthetic-payload ]; then
    printf '%s\\n' 'payload_mismatch' >&2
    exit 22
fi
printf '%s\\n' 'label=demo payload=synthetic-payload'
'''


def run(parent):
    if os.name != 'posix' or not Path('/bin/sh').is_file():
        raise RuntimeError('This drill requires a POSIX system with /bin/sh; recorded run is Linux')
    # The missing-command control must never resolve to somebody else's program.
    if any((Path(directory) / 'lab-job').exists() or (Path(directory) / 'lab-job').is_symlink()
           for directory in ('/usr/bin', '/bin')):
        raise RuntimeError('The synthetic command name already exists on the minimal PATH; refusing to run')
    folder = Path(parent).resolve() / ('job-context-' + uuid.uuid4().hex[:12])
    folder.mkdir(parents=True, exist_ok=False)
    app, tools, neutral = [folder / n for n in ('app with spaces', 'tools with spaces', 'neutral')]
    for path in (app, tools, neutral):
        path.mkdir()
    worker = tools / 'lab-job'
    worker.write_text(WORKER, encoding='utf-8')
    worker.chmod(0o700)
    payload = app / 'payload.txt'
    payload.write_text('synthetic-payload\n', encoding='utf-8')
    base_path = '/usr/bin:/bin'
    baseline = {'PATH': str(tools) + ':' + base_path, 'LLAB_JOB_LABEL': 'demo'}
    absolute_job = shlex.quote(str(worker))
    absolute_input = shlex.quote(str(payload))
    cases = [
        ('explicit_manual_style_context', app, baseline, 'lab-job', [], 0, ''),
        ('custom_bin_absent_from_PATH', app, {'PATH': base_path, 'LLAB_JOB_LABEL': 'demo'}, 'lab-job', [], 127, 'not found'),
        ('absolute_job_relative_input_wrong_cwd', neutral, {'PATH': base_path, 'LLAB_JOB_LABEL': 'demo'}, absolute_job, [], 20, 'input_missing'),
        ('absolute_paths_missing_required_label', neutral, {'PATH': base_path}, absolute_job + ' ' + absolute_input, [], 21, 'label_missing'),
        ('absolute_paths_and_explicit_label', neutral, {'PATH': base_path, 'LLAB_JOB_LABEL': 'demo'}, absolute_job + ' ' + absolute_input, [], 0, ''),
        ('explicit_cd_PATH_and_label', neutral, {'PATH': base_path}, 'cd "$1" && PATH="$2:/usr/bin:/bin" LLAB_JOB_LABEL=demo lab-job', [str(app), str(tools)], 0, ''),
    ]
    records = []
    for name, cwd, env, command, extra, expected_exit, expected_error in cases:
        started = datetime.datetime.now(datetime.timezone.utc).isoformat()
        begin = time.monotonic()
        argv = ['/bin/sh', '-c', command, 'llab-context'] + extra
        completed = subprocess.run(argv, cwd=cwd, env=env, capture_output=True, text=True, timeout=5)
        success_output = 'label=demo payload=synthetic-payload\n'
        checks = {'exit_matches': completed.returncode == expected_exit,
                  'stdout_matches': completed.stdout == (success_output if expected_exit == 0 else ''),
                  'stderr_matches': (not completed.stderr if expected_exit == 0 else expected_error in completed.stderr)}
        record = {'name': name, 'started_at_utc': started,
                  'finished_at_utc': datetime.datetime.now(datetime.timezone.utc).isoformat(),
                  'elapsed_seconds': round(time.monotonic() - begin, 6),
                  'cwd': str(cwd), 'provided_environment': env, 'argv': argv,
                  'expected_exit': expected_exit, 'exit_code': completed.returncode,
                  'stdout': completed.stdout, 'stderr': completed.stderr,
                  'checks': checks, 'passed': all(checks.values())}
        # Only fixture paths occur; normalize them to keep the public record portable.
        records.append(json.loads(json.dumps(record).replace(str(folder), '<fixture>')))
    result = {'experiment': 'six-sequential-shell-execution-context-fixtures',
              'checked_at_utc': datetime.datetime.now(datetime.timezone.utc).isoformat(),
              'python': platform.python_version(), 'platform': platform.system(),
              'kernel': platform.release(), 'shell': '/bin/sh',
              'shell_resolved_name': Path('/bin/sh').resolve().name,
              'fixture_contains_spaces': True, 'cases': records,
              'passed': all(r['passed'] for r in records),
              'cron_daemon_invoked': False, 'crontab_modified': False,
              'production_job_executed': False, 'network_calls': False,
              'host_environment_dumped': False,
              'limits': 'Constructed allowlist environment, cwd and PATH, not a real interactive login or cron daemon. Tiny synthetic reads only. No scheduler timing, account/PAM setup, permissions diagnosis, external service, secret handling, overlap or production job acceptance.'}
    (folder / 'result.json').write_text(json.dumps(result, indent=2) + '\n', encoding='utf-8')
    if not result['passed']:
        raise RuntimeError('Unexpected result; inspect result.json before publishing')
    print(json.dumps({'output': str(folder), 'exit_codes': [r['exit_code'] for r in records],
                      'passed': result['passed'], 'python': result['python'], 'kernel': result['kernel']}))
    return folder


if __name__ == '__main__':
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--out', type=Path, required=True, help='Parent directory for a NEW disposable fixture')
    run(parser.parse_args().out)
