// Code generated by smithy-go-codegen DO NOT EDIT.

package bedrockruntime

import (
	"context"
	"fmt"
	"github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream/eventstreamapi"
	"github.com/aws/aws-sdk-go-v2/service/bedrockruntime/types"
	"github.com/aws/smithy-go/middleware"
	smithysync "github.com/aws/smithy-go/sync"
	smithyhttp "github.com/aws/smithy-go/transport/http"
	"sync"
	"time"
)

// Invoke the specified Amazon Bedrock model to run inference using the
// bidirectional stream. The response is returned in a stream that remains open for
// 8 minutes. A single session can contain multiple prompts and responses from the
// model. The prompts to the model are provided as audio files and the model's
// responses are spoken back to the user and transcribed.
//
// It is possible for users to interrupt the model's response with a new prompt,
// which will halt the response speech. The model will retain contextual awareness
// of the conversation while pivoting to respond to the new prompt.
func (c *Client) InvokeModelWithBidirectionalStream(ctx context.Context, params *InvokeModelWithBidirectionalStreamInput, optFns ...func(*Options)) (*InvokeModelWithBidirectionalStreamOutput, error) {
	if params == nil {
		params = &InvokeModelWithBidirectionalStreamInput{}
	}

	result, metadata, err := c.invokeEventStreamOperation(ctx, "InvokeModelWithBidirectionalStream", params, optFns, c.addOperationInvokeModelWithBidirectionalStreamMiddlewares)
	if err != nil {
		return nil, err
	}

	out := result.(*InvokeModelWithBidirectionalStreamOutput)
	out.ResultMetadata = metadata
	return out, nil
}

type InvokeModelWithBidirectionalStreamInput struct {

	// The model ID or ARN of the model ID to use. Currently, only
	// amazon.nova-sonic-v1:0 is supported.
	//
	// This member is required.
	ModelId *string

	noSmithyDocumentSerde
}

type InvokeModelWithBidirectionalStreamOutput struct {
	eventStream *InvokeModelWithBidirectionalStreamEventStream

	initialReply chan InvokeModelWithBidirectionalStreamInitialReply
	// Metadata pertaining to the operation's result.
	ResultMetadata middleware.Metadata

	noSmithyDocumentSerde
}

// GetStream returns the type to interact with the event stream.
func (o *InvokeModelWithBidirectionalStreamOutput) GetStream() *InvokeModelWithBidirectionalStreamEventStream {
	return o.eventStream
}

type InvokeModelWithBidirectionalStreamInitialReply struct {
	// Metadata pertaining to the operation's result.
	ResultMetadata middleware.Metadata

	noSmithyDocumentSerde
}

func (o *InvokeModelWithBidirectionalStreamOutput) GetInitialReply() <-chan InvokeModelWithBidirectionalStreamInitialReply {
	return o.initialReply
}

func (c *Client) addOperationInvokeModelWithBidirectionalStreamMiddlewares(stack *middleware.Stack, options Options) (err error) {
	err = stack.Serialize.Add(&awsRestjson1_serializeOpInvokeModelWithBidirectionalStream{}, middleware.After)
	if err != nil {
		return err
	}
	err = stack.Deserialize.Add(&awsRestjson1_deserializeOpInvokeModelWithBidirectionalStream{}, middleware.After)
	if err != nil {
		return err
	}

	if err = addlegacyEndpointContextSetter(stack, options); err != nil {
		return err
	}
	if err = addEventStreamInvokeModelWithBidirectionalStreamMiddleware(stack, options); err != nil {
		return err
	}
	if err = smithyhttp.AddRequireMinimumProtocol(stack, 2, 0); err != nil {
		return err
	}
	if err = addEventStreamBuild_opInvokeModelWithBidirectionalStreamMiddleware(stack); err != nil {
		return err
	}
	if err = addResolveEndpointMiddleware(stack, options); err != nil {
		return err
	}
	if err = addStreamingEventsPayload(stack); err != nil {
		return err
	}
	if err = addContentSHA256Header(stack); err != nil {
		return err
	}
	if err = addRecordResponseTiming(stack); err != nil {
		return err
	}
	if err = eventstreamapi.AddInitializeStreamWriter(stack); err != nil {
		return err
	}
	if err = addCredentialSource(stack, options); err != nil {
		return err
	}
	if err = addOpInvokeModelWithBidirectionalStreamValidationMiddleware(stack); err != nil {
		return err
	}
	if err = stack.Initialize.Add(newServiceMetadataMiddleware(options.Region, "InvokeModelWithBidirectionalStream"), middleware.Before); err != nil {
		return err
	}
	if err = addRequestIDRetrieverMiddleware(stack); err != nil {
		return err
	}
	if err = addResponseErrorMiddleware(stack); err != nil {
		return err
	}
	if err = addRequestResponseLogging(stack, options); err != nil {
		return err
	}
	if err = addDisableHTTPSMiddleware(stack, options); err != nil {
		return err
	}
	if err = addInterceptors(stack, options); err != nil {
		return err
	}
	return nil
}

type eventStreamBuild_opInvokeModelWithBidirectionalStreamMiddleware struct {
}

func (*eventStreamBuild_opInvokeModelWithBidirectionalStreamMiddleware) ID() string {
	return "EventStreamBuildMiddleware"
}

func (m *eventStreamBuild_opInvokeModelWithBidirectionalStreamMiddleware) HandleBuild(ctx context.Context, in middleware.BuildInput, next middleware.BuildHandler) (
	out middleware.BuildOutput, metadata middleware.Metadata, err error,
) {
	out, metadata, err = next.HandleBuild(ctx, in)
	res, ok := middleware.GetEventStreamOutputToMetadata[InvokeModelWithBidirectionalStreamOutput](&metadata)
	if !ok {
		return out, metadata, fmt.Errorf("expected to find an object of type InvokeModelWithBidirectionalStreamOutput on metadata, none was found. Metadata %v. Additionally %w", metadata, err)
	}
	if err != nil {
		// fail the event stream because the middleware failed
		res.eventStream.err.SetError(err)
		res.GetStream().Close()
	}
	initialReply, ok := out.Result.(*InvokeModelWithBidirectionalStreamInitialReply)
	_ = initialReply
	if !ok {
		// set an initial reply with just the metadata. Error was set above
		response := InvokeModelWithBidirectionalStreamInitialReply{
			ResultMetadata: metadata,
		}
		res.initialReply <- response
		return out, metadata, fmt.Errorf("unexpected type of result. expected InvokeModelWithBidirectionalStreamInitialReply, got %T. Additionally %w", out.Result, err)
	}
	response := InvokeModelWithBidirectionalStreamInitialReply{
		ResultMetadata: metadata,
	}
	res.initialReply <- response
	return out, metadata, err
}
func addEventStreamBuild_opInvokeModelWithBidirectionalStreamMiddleware(stack *middleware.Stack) error {
	return stack.Build.Add(&eventStreamBuild_opInvokeModelWithBidirectionalStreamMiddleware{}, middleware.Before)
}

// InvokeModelWithBidirectionalStreamEventStream provides the event stream handling for the InvokeModelWithBidirectionalStream operation.
//
// For testing and mocking the event stream this type should be initialized via
// the NewInvokeModelWithBidirectionalStreamEventStream constructor function. Using the functional options
// to pass in nested mock behavior.
type InvokeModelWithBidirectionalStreamEventStream struct {
	// InvokeModelWithBidirectionalStreamInputWriter is the EventStream writer for the
	// InvokeModelWithBidirectionalStreamInput events. This value is automatically set
	// by the SDK when the API call is made Use this member when unit testing your code
	// with the SDK to mock out the EventStream Writer.
	//
	// Must not be nil.
	Writer InvokeModelWithBidirectionalStreamInputWriter

	// InvokeModelWithBidirectionalStreamOutputReader is the EventStream reader for
	// the InvokeModelWithBidirectionalStreamOutput events. This value is automatically
	// set by the SDK when the API call is made Use this member when unit testing your
	// code with the SDK to mock out the EventStream Reader.
	//
	// Must not be nil.
	Reader InvokeModelWithBidirectionalStreamOutputReader

	done      chan struct{}
	closeOnce sync.Once
	err       *smithysync.OnceErr
}

// NewInvokeModelWithBidirectionalStreamEventStream initializes an InvokeModelWithBidirectionalStreamEventStream.
// This function should only be used for testing and mocking the InvokeModelWithBidirectionalStreamEventStream
// stream within your application.
//
// The Writer member must be set before writing events to the stream.
//
// The Reader member must be set before reading events from the stream.
func NewInvokeModelWithBidirectionalStreamEventStream(optFns ...func(*InvokeModelWithBidirectionalStreamEventStream)) *InvokeModelWithBidirectionalStreamEventStream {
	es := &InvokeModelWithBidirectionalStreamEventStream{
		done: make(chan struct{}),
		err:  smithysync.NewOnceErr(),
	}
	for _, fn := range optFns {
		fn(es)
	}
	return es
}

// Send writes the event to the stream blocking until the event is written.
// Returns an error if the event was not written.
func (es *InvokeModelWithBidirectionalStreamEventStream) Send(ctx context.Context, event types.InvokeModelWithBidirectionalStreamInput) error {
	return es.Writer.Send(ctx, event)
}

// Events returns a channel to read events from.
func (es *InvokeModelWithBidirectionalStreamEventStream) Events() <-chan types.InvokeModelWithBidirectionalStreamOutput {
	return es.Reader.Events()
}

// Close closes the stream. This will also cause the stream to be closed.
// Close must be called when done using the stream API. Not calling Close
// may result in resource leaks.
//
// Will close the underlying EventStream writer and reader, and no more events can be
// sent or received.
func (es *InvokeModelWithBidirectionalStreamEventStream) Close() error {
	es.closeOnce.Do(es.safeClose)
	return es.Err()
}

func (es *InvokeModelWithBidirectionalStreamEventStream) safeClose() {
	close(es.done)

	t := time.NewTicker(time.Second)
	defer t.Stop()
	writeCloseDone := make(chan error)
	go func() {
		if err := es.Writer.Close(); err != nil {
			es.err.SetError(err)
		}
		close(writeCloseDone)
	}()
	select {
	case <-t.C:
	case <-writeCloseDone:
	}

	es.Reader.Close()
}

// Err returns any error that occurred while reading or writing EventStream Events
// from the service API's response. Returns nil if there were no errors.
func (es *InvokeModelWithBidirectionalStreamEventStream) Err() error {
	if err := es.err.Err(); err != nil {
		return err
	}

	if err := es.Writer.Err(); err != nil {
		return err
	}

	if err := es.Reader.Err(); err != nil {
		return err
	}

	return nil
}

func (es *InvokeModelWithBidirectionalStreamEventStream) waitStreamClose() {
	type errorSet interface {
		ErrorSet() <-chan struct{}
	}

	var inputErrCh <-chan struct{}
	if v, ok := es.Writer.(errorSet); ok {
		inputErrCh = v.ErrorSet()
	}

	var outputErrCh <-chan struct{}
	if v, ok := es.Reader.(errorSet); ok {
		outputErrCh = v.ErrorSet()
	}
	var outputClosedCh <-chan struct{}
	if v, ok := es.Reader.(interface{ Closed() <-chan struct{} }); ok {
		outputClosedCh = v.Closed()
	}

	select {
	case <-es.done:
	case <-inputErrCh:
		es.err.SetError(es.Writer.Err())
		es.Close()

	case <-outputErrCh:
		es.err.SetError(es.Reader.Err())
		es.Close()

	case <-outputClosedCh:
		if err := es.Reader.Err(); err != nil {
			es.err.SetError(es.Reader.Err())
		}
		es.Close()

	}
}
