"""Prototype for Ubuntu WSL; not a hardened multi-tenant security boundary."""
import json, os, selectors, signal, subprocess, tempfile, time
from pathlib import Path

BOOT = Path(__file__).resolve().with_name('sandbox_boot.sh')

def run_actions(actions, timeout=5.0, mem_limit=128*1024*1024, max_bytes=32768):
    if not isinstance(actions,list) or not actions or len(actions)>8 or any(not isinstance(x,str) or len(x)>10000 for x in actions):
        raise ValueError('actions must be 1..8 strings of at most 10000 characters')
    if timeout <= 0 or not 48*1024*1024 <= mem_limit <= 512*1024*1024:
        raise ValueError('invalid resource limit')
    payload=(json.dumps({'actions':actions,'mem_limit':mem_limit})+'\n').encode()
    data=bytearray(); reason=None
    with tempfile.TemporaryDirectory(prefix='oryon-sandbox-') as root:
        deadline=time.monotonic()+timeout
        p = subprocess.Popen(['unshare','--user','--map-root-user','--mount','--net','--pid','--fork','--kill-child','sh',str(BOOT),root],
            stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.STDOUT,start_new_session=True,
            env={'PATH':'/usr/sbin:/usr/bin:/sbin:/bin','LANG':'C.UTF-8'})
        sel=selectors.DefaultSelector()
        os.set_blocking(p.stdin.fileno(),False)
        sel.register(p.stdin,selectors.EVENT_WRITE,'stdin')
        sel.register(p.stdout,selectors.EVENT_READ,'stdout')
        sent=0
        try:
            while sel.get_map():
                remaining=deadline-time.monotonic()
                if remaining <= 0: reason='timeout'; break
                events=sel.select(remaining)
                if not events: reason='timeout'; break
                for key,_ in events:
                    if key.data=='stdin':
                        try:
                            sent += os.write(p.stdin.fileno(),payload[sent:sent+4096])
                        except BrokenPipeError:
                            sent=len(payload)
                        if sent==len(payload):
                            sel.unregister(p.stdin); p.stdin.close()
                    else:
                        chunk=os.read(p.stdout.fileno(),4096)
                        if not chunk:
                            sel.unregister(p.stdout); p.stdout.close(); continue
                        data.extend(chunk)
                        if len(data)>max_bytes: reason='output_limit'; break
                if reason: break
            if not reason:
                try:
                    p.wait(timeout=max(0,deadline-time.monotonic()))
                except subprocess.TimeoutExpired:
                    reason='timeout'
            if reason:
                try: os.killpg(p.pid,signal.SIGKILL)
                except ProcessLookupError: pass
            p.wait()
        finally:
            sel.close()
            if p.poll() is None:
                try: os.killpg(p.pid,signal.SIGKILL)
                except ProcessLookupError: pass
                p.wait()
    if reason:return {'status':reason,'output':bytes(data[:max_bytes]).decode('utf8','replace')}
    if p.returncode != 0:return {'status':'setup_or_process_error','output':bytes(data[:max_bytes]).decode('utf8','replace')}
    try:return {'status':'ok','result':json.loads(data)}
    except json.JSONDecodeError:return {'status':'invalid_protocol','output':bytes(data[:max_bytes]).decode('utf8','replace')}

def run_sandboxed(code, timeout=5.0, mem_limit=128*1024*1024):
    return run_actions([code],timeout,mem_limit)
