<?php

declare(strict_types=1);

namespace Blax\WebRtc\Realtime;

use Blax\WebRtc\Contracts\RealtimeTransport;
use WebSocket\Client as WebSocketClient;

/**
 * {@see RealtimeTransport} over textalk/websocket (a blocking WS client). This is
 * the default transport for {@see OpenAiRealtimeBridge}: fine for a turn-based
 * bridge where each turn opens, drives and closes one provider session, and it
 * fits a fork-per-message host (the whole turn runs inside one request/worker).
 */
final class TextalkRealtimeTransport implements RealtimeTransport
{
    private WebSocketClient $client;

    /** @param array<string,string> $headers */
    public function __construct(string $url, array $headers, int $timeout)
    {
        $this->client = new WebSocketClient($url, [
            'headers' => $headers,
            'timeout' => $timeout,
        ]);
    }

    public function send(string $text): void
    {
        $this->client->text($text);
    }

    public function receive(): ?string
    {
        try {
            $raw = $this->client->receive();
        } catch (\Throwable) {
            return null; // timeout / closed
        }

        return is_string($raw) ? $raw : null;
    }

    public function close(): void
    {
        try {
            $this->client->close();
        } catch (\Throwable) {
            // ignore
        }
    }
}
