"""Sesión Linux aislada con acciones interactivas; prototipo, no frontera endurecida."""
import json
import os
from pathlib import Path
import selectors
import signal
import subprocess
import tempfile
import time

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


class SandboxSession:
    def __init__(self,timeout=30,mem_limit=128*1024*1024,max_bytes=32768):
        if timeout<=0 or not 48*1024*1024<=mem_limit<=512*1024*1024 or max_bytes<1024:
            raise ValueError('invalid limits')
        self.timeout=timeout;self.max_bytes=max_bytes;self.buffer=bytearray();self.dead=False
        self.temp=tempfile.TemporaryDirectory(prefix='oryon-session-')
        try:
            self.process=subprocess.Popen(['unshare','--user','--map-root-user','--mount','--net','--pid','--fork','--kill-child','sh',str(BOOT),self.temp.name],
                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'})
            os.set_blocking(self.process.stdin.fileno(),False);os.set_blocking(self.process.stdout.fileno(),False)
            if self._exchange({'mem_limit':mem_limit})!={'ready':True}:raise RuntimeError('invalid setup response')
        except BaseException:
            self.close();raise

    def _exchange(self,message):
        if self.dead:raise RuntimeError('session is closed')
        payload=(json.dumps(message)+'\n').encode();sent=0
        deadline=time.monotonic()+self.timeout
        selector=selectors.DefaultSelector()
        selector.register(self.process.stdin,selectors.EVENT_WRITE,'write')
        selector.register(self.process.stdout,selectors.EVENT_READ,'read')
        try:
            while True:
                remaining=deadline-time.monotonic()
                if remaining<=0:raise TimeoutError('sandbox session timed out')
                events=selector.select(remaining)
                if not events:raise TimeoutError('sandbox session timed out')
                for key,_ in events:
                    if key.data=='write':
                        sent+=os.write(key.fd,payload[sent:sent+4096])
                        if sent==len(payload):selector.unregister(self.process.stdin)
                    else:
                        chunk=os.read(key.fd,4096)
                        if not chunk:raise RuntimeError('sandbox session closed unexpectedly')
                        self.buffer.extend(chunk)
                        if len(self.buffer)>self.max_bytes:raise RuntimeError('sandbox protocol output too large')
                        if b'\n' in self.buffer:
                            line,remainder=self.buffer.split(b'\n',1);self.buffer=bytearray(remainder)
                            try:result=json.loads(line)
                            except (ValueError,UnicodeDecodeError) as exc:raise RuntimeError('invalid sandbox protocol') from exc
                            return result
        except BaseException:
            self.close();raise
        finally:selector.close()

    def execute(self,code):
        if not isinstance(code,str) or len(code)>10000:raise ValueError('invalid action')
        result=self._exchange({'code':code})
        if not isinstance(result,dict) or result.get('status') not in ('ok','error') or not isinstance(result.get('output'),str):
            self.close();raise RuntimeError('invalid action response')
        return result

    def close(self):
        if self.dead:return
        self.dead=True
        proc=getattr(self,'process',None)
        if proc is not None:
            if proc.poll() is None:
                try:os.killpg(proc.pid,signal.SIGKILL)
                except ProcessLookupError:pass
            proc.wait()
            for stream in (proc.stdin,proc.stdout):
                if stream:stream.close()
        self.temp.cleanup()

    def __enter__(self):return self
    def __exit__(self,*args):self.close()
