import asyncio
import aiohttp
import aiohttp.web
import os
import pty
import shlex
import subprocess
import pathlib

commands = {
    'alpine': 'docker run -it alpine /bin/sh',
    'r': 'docker run -v /usr/local/bin:/usr/local/bin -it ubuntu:latest run.sh',
}

class TerminalSession:
    def __init__(self,command):
        self.master, self.slave = pty.openpty()
        self.sockets =[]
        self.process = subprocess.Popen(
            command.split(" "),
            stdin=self.slave,
            stdout=self.slave,
            stderr=self.slave,
            bufsize=0,
            universal_newlines=True
        )

    async def read_output(self, ws):
        loop = asyncio.get_event_loop()
        self.sockets.append(ws)
        if len(self.sockets) > 1:
            return 
        while True:
            try:
                data = await loop.run_in_executor(None, os.read, self.master, 1024)
                if not data:
                    break
                try:
                    for ws in self.sockets: await ws.send_bytes(data)  # Send raw bytes for ANSI support
                except:
                    self.sockets.remove(ws)
            except Exception:
                break

    async def write_input(self, data):
        os.write(self.master, data.encode())


