/**
 * Stream signaling client — connects to the backend WebSocket endpoint
 * for WebRTC signaling relay.
 *
 * The backend only relays SDP offers/answers and ICE candidates between
 * the streamer (this extension) and viewers. No media passes through.
 */
import WebSocket from "ws";
export class SignalingClient {
    config;
    ws = null;
    connected = false;
    constructor(config) {
        this.config = config;
    }
    async connect() {
        return new Promise((resolve, reject) => {
            const timeout = setTimeout(() => reject(new Error("Signaling connection timeout")), 10_000);
            this.ws = new WebSocket(this.config.signalingUrl);
            this.ws.on("open", () => {
                clearTimeout(timeout);
                this.connected = true;
                this.ws.send(JSON.stringify({
                    type: "create-session",
                    sessionId: this.config.sessionId,
                }));
                resolve();
            });
            this.ws.on("error", (err) => {
                clearTimeout(timeout);
                reject(err);
            });
            this.ws.on("message", (data) => {
                try {
                    const msg = JSON.parse(data.toString());
                    this.handleMessage(msg);
                }
                catch {
                    // Ignore malformed messages
                }
            });
        });
    }
    handleMessage(msg) {
        // Messages are primarily forwarded to the in-browser WebRTC client
        // via page.evaluate(). This client just logs them.
        if (msg.type === "viewer-joined") {
            process.stderr.write(`[browser-stream] Viewer joined: ${msg.viewerId}\n`);
        }
        if (msg.type === "viewer-left") {
            process.stderr.write(`[browser-stream] Viewer left: ${msg.viewerId}\n`);
        }
    }
    send(data) {
        if (this.ws && this.connected) {
            this.ws.send(JSON.stringify(data));
        }
    }
    close() {
        if (this.ws) {
            this.ws.close();
            this.ws = null;
            this.connected = false;
        }
    }
    isConnected() {
        return this.connected;
    }
}
