<?php

namespace Libs;

class BashExecutor
{
    public static function run(string $command, int $timeoutSeconds = 30): array
    {
        $descriptorSpec = [
            0 => ["pipe", "r"],   // STDIN
            1 => ["pipe", "w"],   // STDOUT
            2 => ["pipe", "w"]    // STDERR
        ];

        $process = proc_open($command, $descriptorSpec, $pipes);

        if (!is_resource($process)) {
            return [
                "exitCode" => -1,
                "output" => "",
                "error" => "Failed to start process"
            ];
        }

        // Timeout handling
        $start = time();
        $stdout = "";
        $stderr = "";

        do {
            $status = proc_get_status($process);

            $stdout .= stream_get_contents($pipes[1]);
            $stderr .= stream_get_contents($pipes[2]);

            usleep(5000000); // 0.1 segundo

            if ((time() - $start) > $timeoutSeconds) {
                proc_terminate($process);
                return [
                    "exitCode" => -1,
                    "output" => $stdout,
                    "error" => "Timeout of {$timeoutSeconds}s reached"
                ];
            }

        } while ($status['running']);

        foreach ($pipes as $pipe) {
            fclose($pipe);
        }

        $lastStatusExitCode = $status['exitcode'] ?? null;
        $closeExitCode = proc_close($process);
        $exitCode = ($lastStatusExitCode === null || $lastStatusExitCode === -1)
            ? $closeExitCode
            : $lastStatusExitCode;

        return [
            "exitCode" => $exitCode,
            "output" => trim($stdout),
            "error" => trim($stderr)
        ];
    }
}