<?php

declare(strict_types=1);

namespace Blax\WebRtc\Console\Commands;

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

/**
 * Explicit form of what RustMediaEngine does plug-and-play on first use:
 * download the prebuilt, checksummed SFU sidecar binary for this platform.
 */
class InstallSfuBinary extends Command
{
    protected $signature = 'webrtc:install {--force : Redownload even when already installed}';

    protected $description = 'Download the prebuilt blax-webrtc-sfu sidecar binary (Rust data plane) for this platform.';

    public function handle(BinaryManager $binaries): int
    {
        if (! $this->option('force') && ($found = $binaries->find())) {
            $this->info("SFU sidecar already available: {$found}");

            return self::SUCCESS;
        }

        $this->line("Installing blax-webrtc-sfu {$binaries->version()} for {$binaries->platform()} …");

        try {
            $path = $binaries->install((bool) $this->option('force'));
        } catch (SidecarException $e) {
            $this->error($e->getMessage());

            return self::FAILURE;
        }

        $this->info("Installed: {$path}");

        return self::SUCCESS;
    }
}
