package oci

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

	"github.com/oracle/oci-go-sdk/v65/common"
)

// compatSpeechLimit 限制 TTS 音频响应体大小(长文本 mp3 给足余量)。
const compatSpeechLimit = int64(64 << 20)

// GenAiCompatSpeech 实现 Client:把 OpenAI Audio Speech 请求体直通到 OCI
// 兼容面 `/openai/v1/audio/speech`(IAM 签名,BasePath 置空——该面与
// /20231130/actions 面并存,实测仅前者承载 TTS)。返回音频字节与 Content-Type。
func (c *RealClient) GenAiCompatSpeech(ctx context.Context, cred Credentials, region string, body []byte) ([]byte, string, error) {
	ic, err := c.genAiInferenceClient(cred, region)
	if err != nil {
		return nil, "", err
	}
	client := ic.BaseClient
	common.UpdateEndpointTemplateForOptions(&client)
	common.SetMissingTemplateParams(&client)
	client.BasePath = ""
	request, err := http.NewRequestWithContext(ctx, http.MethodPost, "/openai/v1/audio/speech", bytes.NewReader(body))
	if err != nil {
		return nil, "", fmt.Errorf("build compat speech request: %w", err)
	}
	request.Header.Set("Content-Type", "application/json")
	request.Header.Set("opc-compartment-id", cred.TenancyOCID)
	response, err := client.Call(ctx, request)
	if err != nil {
		return nil, "", err
	}
	defer response.Body.Close()
	payload, err := io.ReadAll(io.LimitReader(response.Body, compatSpeechLimit))
	if err != nil {
		return nil, "", fmt.Errorf("read compat speech body: %w", err)
	}
	return payload, response.Header.Get("Content-Type"), nil
}
