// Copyright (c) 2026 Alibaba Group and its affiliates

// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at

//     http://www.apache.org/licenses/LICENSE-2.0

// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package sdk

import (
	"context"
	"fmt"
	"net/http"

	"github.com/gorilla/websocket"
)

// dialWebSocket establishes WebSocket connection to DashScope gateway
func dialWebSocket(ctx context.Context, endpoint, apiKey string) (*websocket.Conn, error) {
	// Set up HTTP headers for authentication
	headers := http.Header{}
	headers.Add("Authorization", "Bearer "+apiKey)

	// Create custom dialer with buffer sizes for WebSocket frame fragmentation
	dialer := websocket.Dialer{
		ReadBufferSize:  128 * 1024, // 128KB
		WriteBufferSize: 128 * 1024, // 128KB — messages larger than this are fragmented into continuation frames
	}

	// Dial WebSocket with context
	conn, _, err := dialer.DialContext(ctx, endpoint, headers)
	if err != nil {
		return nil, fmt.Errorf("failed to dial WebSocket: %w", err)
	}

	return conn, nil
}
