<?php

declare(strict_types=1);

namespace Blax\WebRtc\Console\Commands;

use Blax\WebRtc\Media\Rust\BinaryManager;
use Blax\WebRtc\Media\Rust\SidecarException;
use Blax\WebRtc\Media\Rust\SidecarSupervisor;
use Illuminate\Console\Command;

/**
 * Run the Rust SFU sidecar in the FOREGROUND — for docker services / process
 * supervisors (set webrtc.sfu.auto_spawn=false there so workers don't race
 * their own detached copy). Uses pcntl_exec when available so the binary
 * replaces this process and receives signals directly.
 */
class RunSfuSidecar extends Command
{
    protected $signature = 'webrtc:sidecar';

    protected $description = 'Run the blax-webrtc-sfu sidecar (Rust data plane) in the foreground.';

    public function handle(BinaryManager $binaries, SidecarSupervisor $supervisor): int
    {
        try {
            $binary = $binaries->ensureInstalled();
        } catch (SidecarException $e) {
            $this->error($e->getMessage());

            return self::FAILURE;
        }

        $args = $supervisor->args();
        $this->info("exec {$binary} ".implode(' ', $args));

        if (\function_exists('pcntl_exec')) {
            pcntl_exec($binary, $args); // only returns on failure

            $this->error('pcntl_exec failed');

            return self::FAILURE;
        }

        passthru(
            escapeshellarg($binary).' '.implode(' ', array_map('escapeshellarg', $args)),
            $exit,
        );

        return $exit;
    }
}
