import { WebSocketServer } from "ws";
export function createWebSocketServer(httpServer, bridge) {
    const wss = new WebSocketServer({ server: httpServer });
    wss.on("connection", (ws) => {
        ws.on("message", (raw) => {
            let msg;
            try {
                msg = JSON.parse(String(raw));
            }
            catch {
                return;
            }
            if (msg.type === "chat") {
                if (bridge.isBusy()) {
                    ws.send(JSON.stringify({ type: "busy" }));
                    return;
                }
                bridge.runTurn(msg.message).catch(() => {
                    // errors already broadcast via agent-bridge
                });
            }
            else if (msg.type === "cancel") {
                bridge.cancel();
            }
            else if (msg.type === "switch_model") {
                bridge.switchModel(msg.model);
                const changed = { type: "model_changed", model: msg.model };
                // Broadcast to all clients
                for (const client of wss.clients) {
                    client.send(JSON.stringify(changed));
                }
            }
            else if (msg.type === "permission_response") {
                bridge.resolvePermissionRequest(msg.requestId, {
                    decision: msg.decision,
                    ...(msg.setAutoAllowMode !== undefined
                        ? { setAutoAllowMode: msg.setAutoAllowMode }
                        : {}),
                });
            }
            else if (msg.type === "set_auto_allow_mode") {
                bridge.setAutoAllowMode(msg.mode);
            }
        });
    });
    return wss;
}
