"""Puente Windows→WSL para una sesión persistente local de sandbox."""
import json
import queue
import subprocess
import threading


class WSLSession:
    def __init__(self,linux_cli,timeout=45):
        self.timeout=timeout;self.queue=queue.Queue();self.closed=False
        self.process=subprocess.Popen(['wsl','-d','Ubuntu','--','python3',linux_cli],
            stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.STDOUT)
        def read():
            while True:
                line=self.process.stdout.readline(65537)
                self.queue.put(line)
                if not line:break
        self.reader=threading.Thread(target=read,daemon=True);self.reader.start()
        try:
            if self._read()!={'ready':True}:raise RuntimeError('invalid session readiness')
        except BaseException:
            self.close();raise

    def _read(self):
        try:line=self.queue.get(timeout=self.timeout)
        except queue.Empty as exc:raise TimeoutError('WSL session bridge timed out') from exc
        if not line or len(line)>65536 or not line.endswith(b'\n'):
            raise RuntimeError('WSL session protocol ended or exceeded limit')
        try:value=json.loads(line.decode('utf8'))
        except (ValueError,UnicodeDecodeError) as exc:raise RuntimeError('invalid WSL session protocol') from exc
        if not isinstance(value,dict) or 'error' in value:raise RuntimeError('sandbox session inconclusive: '+str(value))
        return value

    def execute(self,code):
        if self.closed:raise RuntimeError('WSL session closed')
        try:
            self.process.stdin.write((json.dumps({'code':code})+'\n').encode());self.process.stdin.flush()
            value=self._read()
            if set(value)!={'result'} or not isinstance(value['result'],dict):raise RuntimeError('invalid action response')
            return value['result']
        except BaseException:
            self.close();raise

    def close(self):
        if self.closed:return
        self.closed=True
        if self.process.poll() is None:
            try:self.process.stdin.write(b'{"close":true}\n');self.process.stdin.flush();self.process.stdin.close()
            except (OSError,ValueError):pass
            try:self.process.wait(timeout=35)
            except subprocess.TimeoutExpired:self.process.terminate();self.process.wait()
        if self.process.stdin and not self.process.stdin.closed:self.process.stdin.close()
        self.reader.join(timeout=1)
        self.process.stdout.close()

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