// Code generated by protoc-gen-go_temporal. DO NOT EDIT.
// versions:
//
//	protoc-gen-go_temporal dev (latest)
//	protoc (unknown)
//
// source: example/schedule/v1/schedule.proto
package schedulev1

import (
	"bytes"
	"context"
	"encoding/json"
	"errors"
	"fmt"
	helpers "github.com/cludden/protoc-gen-go-temporal/pkg/helpers"
	scheme "github.com/cludden/protoc-gen-go-temporal/pkg/scheme"
	gohomedir "github.com/mitchellh/go-homedir"
	v2 "github.com/urfave/cli/v2"
	enumsv1 "go.temporal.io/api/enums/v1"
	client "go.temporal.io/sdk/client"
	converter "go.temporal.io/sdk/converter"
	temporal "go.temporal.io/sdk/temporal"
	testsuite "go.temporal.io/sdk/testsuite"
	worker "go.temporal.io/sdk/worker"
	workflow "go.temporal.io/sdk/workflow"
	protojson "google.golang.org/protobuf/encoding/protojson"
	protoreflect "google.golang.org/protobuf/reflect/protoreflect"
	"log/slog"
	"os"
	"sort"
	"sync"
	"sync/atomic"
	"time"
)

// ExampleTaskQueue is the default task-queue for a example.schedule.v1.Example worker
var ExampleTaskQueue = "schedule-v1"

// example.schedule.v1.Example workflow names
const (
	ScheduleWorkflowName = "example.schedule.v1.Schedule"
)

// ExampleClient describes a client for a(n) example.schedule.v1.Example worker
type ExampleClient interface {
	// Schedule executes a(n) example.schedule.v1.Schedule workflow and blocks until error or response received
	Schedule(ctx context.Context, req *ScheduleInput, opts ...*ScheduleOptions) (*ScheduleOutput, error)

	// ScheduleAsync starts a(n) example.schedule.v1.Schedule workflow and returns a handle to the workflow run
	ScheduleAsync(ctx context.Context, req *ScheduleInput, opts ...*ScheduleOptions) (ScheduleRun, error)

	// GetSchedule retrieves a handle to an existing example.schedule.v1.Schedule workflow execution
	GetSchedule(ctx context.Context, workflowID string, runID string) ScheduleRun

	// CancelWorkflow requests cancellation of an existing workflow execution
	CancelWorkflow(ctx context.Context, workflowID string, runID string) error

	// TerminateWorkflow an existing workflow execution
	TerminateWorkflow(ctx context.Context, workflowID string, runID string, reason string, details ...interface{}) error
}

// exampleClient implements a temporal client for a example.schedule.v1.Example service
type exampleClient struct {
	client client.Client
	log    *slog.Logger
}

// NewExampleClient initializes a new example.schedule.v1.Example client
func NewExampleClient(c client.Client, options ...*exampleClientOptions) ExampleClient {
	var cfg *exampleClientOptions
	if len(options) > 0 {
		cfg = options[0]
	} else {
		cfg = NewExampleClientOptions()
	}
	return &exampleClient{
		client: c,
		log:    cfg.getLogger(),
	}
}

// NewExampleClientWithOptions initializes a new Example client with the given options
func NewExampleClientWithOptions(c client.Client, opts client.Options, options ...*exampleClientOptions) (ExampleClient, error) {
	var err error
	c, err = client.NewClientFromExisting(c, opts)
	if err != nil {
		return nil, fmt.Errorf("error initializing client with options: %w", err)
	}
	var cfg *exampleClientOptions
	if len(options) > 0 {
		cfg = options[0]
	} else {
		cfg = NewExampleClientOptions()
	}
	return &exampleClient{
		client: c,
		log:    cfg.getLogger(),
	}, nil
}

// exampleClientOptions describes optional runtime configuration for a ExampleClient
type exampleClientOptions struct {
	log *slog.Logger
}

// NewExampleClientOptions initializes a new exampleClientOptions value
func NewExampleClientOptions() *exampleClientOptions {
	return &exampleClientOptions{}
}

// WithLogger can be used to override the default logger
func (opts *exampleClientOptions) WithLogger(l *slog.Logger) *exampleClientOptions {
	if l != nil {
		opts.log = l
	}
	return opts
}

// getLogger returns the configured logger, or the default logger
func (opts *exampleClientOptions) getLogger() *slog.Logger {
	if opts != nil && opts.log != nil {
		return opts.log
	}
	return slog.Default()
}

// example.schedule.v1.Example.Schedule executes a example.schedule.v1.Schedule workflow and blocks until error or response received
func (c *exampleClient) Schedule(ctx context.Context, req *ScheduleInput, options ...*ScheduleOptions) (*ScheduleOutput, error) {
	run, err := c.ScheduleAsync(ctx, req, options...)
	if err != nil {
		return nil, err
	}
	return run.Get(ctx)
}

// ScheduleAsync starts a(n) example.schedule.v1.Schedule workflow and returns a handle to the workflow run
func (c *exampleClient) ScheduleAsync(ctx context.Context, req *ScheduleInput, options ...*ScheduleOptions) (ScheduleRun, error) {
	var o *ScheduleOptions
	if len(options) > 0 && options[0] != nil {
		o = options[0]
	} else {
		o = NewScheduleOptions()
	}
	opts, err := o.Build(req.ProtoReflect())
	if err != nil {
		return nil, fmt.Errorf("error initializing client.StartWorkflowOptions: %w", err)
	}
	run, err := c.client.ExecuteWorkflow(ctx, opts, ScheduleWorkflowName, req)
	if err != nil {
		return nil, err
	}
	if run == nil {
		return nil, errors.New("execute workflow returned nil run")
	}
	return &scheduleRun{
		client: c,
		run:    run,
	}, nil
}

// GetSchedule fetches an existing example.schedule.v1.Schedule execution
func (c *exampleClient) GetSchedule(ctx context.Context, workflowID string, runID string) ScheduleRun {
	return &scheduleRun{
		client: c,
		run:    c.client.GetWorkflow(ctx, workflowID, runID),
	}
}

// CancelWorkflow requests cancellation of an existing workflow execution
func (c *exampleClient) CancelWorkflow(ctx context.Context, workflowID string, runID string) error {
	return c.client.CancelWorkflow(ctx, workflowID, runID)
}

// TerminateWorkflow terminates an existing workflow execution
func (c *exampleClient) TerminateWorkflow(ctx context.Context, workflowID string, runID string, reason string, details ...interface{}) error {
	return c.client.TerminateWorkflow(ctx, workflowID, runID, reason, details...)
}

// ScheduleOptions provides configuration for a example.schedule.v1.Schedule workflow operation
type ScheduleOptions struct {
	options                  client.StartWorkflowOptions
	executionTimeout         *time.Duration
	id                       *string
	idReusePolicy            enumsv1.WorkflowIdReusePolicy
	retryPolicy              *temporal.RetryPolicy
	runTimeout               *time.Duration
	searchAttributes         map[string]any
	taskQueue                *string
	taskTimeout              *time.Duration
	workflowIdConflictPolicy enumsv1.WorkflowIdConflictPolicy
}

// NewScheduleOptions initializes a new ScheduleOptions value
func NewScheduleOptions() *ScheduleOptions {
	return &ScheduleOptions{}
}

// Build initializes a new go.temporal.io/sdk/client.StartWorkflowOptions value with defaults and overrides applied
func (o *ScheduleOptions) Build(req protoreflect.Message) (client.StartWorkflowOptions, error) {
	opts := o.options
	if v := o.id; v != nil {
		opts.ID = *v
	}
	if v := o.idReusePolicy; v != enumsv1.WORKFLOW_ID_REUSE_POLICY_UNSPECIFIED {
		opts.WorkflowIDReusePolicy = v
	}
	if v := o.workflowIdConflictPolicy; v != enumsv1.WORKFLOW_ID_CONFLICT_POLICY_UNSPECIFIED {
		opts.WorkflowIDConflictPolicy = v
	}
	if v := o.taskQueue; v != nil {
		opts.TaskQueue = *v
	} else if opts.TaskQueue == "" {
		opts.TaskQueue = ExampleTaskQueue
	}
	if v := o.retryPolicy; v != nil {
		opts.RetryPolicy = v
	}
	if v := o.searchAttributes; v != nil {
		opts.SearchAttributes = o.searchAttributes
	}
	if v := o.executionTimeout; v != nil {
		opts.WorkflowExecutionTimeout = *v
	}
	if v := o.runTimeout; v != nil {
		opts.WorkflowRunTimeout = *v
	}
	if v := o.taskTimeout; v != nil {
		opts.WorkflowTaskTimeout = *v
	}
	return opts, nil
}

// WithStartWorkflowOptions sets the initial go.temporal.io/sdk/client.StartWorkflowOptions
func (o *ScheduleOptions) WithStartWorkflowOptions(options client.StartWorkflowOptions) *ScheduleOptions {
	o.options = options
	return o
}

// WithExecutionTimeout sets the WorkflowExecutionTimeout value
func (o *ScheduleOptions) WithExecutionTimeout(d time.Duration) *ScheduleOptions {
	o.executionTimeout = &d
	return o
}

// WithID sets the ID value
func (o *ScheduleOptions) WithID(id string) *ScheduleOptions {
	o.id = &id
	return o
}

// WithIDReusePolicy sets the WorkflowIDReusePolicy value
func (o *ScheduleOptions) WithIDReusePolicy(policy enumsv1.WorkflowIdReusePolicy) *ScheduleOptions {
	o.idReusePolicy = policy
	return o
}

// WithRetryPolicy sets the RetryPolicy value
func (o *ScheduleOptions) WithRetryPolicy(policy *temporal.RetryPolicy) *ScheduleOptions {
	o.retryPolicy = policy
	return o
}

// WithRunTimeout sets the WorkflowRunTimeout value
func (o *ScheduleOptions) WithRunTimeout(d time.Duration) *ScheduleOptions {
	o.runTimeout = &d
	return o
}

// WithSearchAttributes sets the SearchAttributes value
func (o *ScheduleOptions) WithSearchAttributes(sa map[string]any) *ScheduleOptions {
	o.searchAttributes = sa
	return o
}

// WithTaskTimeout sets the WorkflowTaskTimeout value
func (o *ScheduleOptions) WithTaskTimeout(d time.Duration) *ScheduleOptions {
	o.taskTimeout = &d
	return o
}

// WithTaskQueue sets the TaskQueue value
func (o *ScheduleOptions) WithTaskQueue(tq string) *ScheduleOptions {
	o.taskQueue = &tq
	return o
}

// WithWorkflowIdConflictPolicy sets the WorkflowIdConflictPolicy value
func (o *ScheduleOptions) WithWorkflowIdConflictPolicy(policy enumsv1.WorkflowIdConflictPolicy) *ScheduleOptions {
	o.workflowIdConflictPolicy = policy
	return o
}

// ScheduleRun describes a(n) example.schedule.v1.Schedule workflow run
type ScheduleRun interface {
	// ID returns the workflow ID
	ID() string

	// RunID returns the workflow instance ID
	RunID() string

	// Run returns the inner client.WorkflowRun
	Run() client.WorkflowRun

	// Get blocks until the workflow is complete and returns the result
	Get(ctx context.Context) (*ScheduleOutput, error)

	// Cancel requests cancellation of a workflow in execution, returning an error if applicable
	Cancel(ctx context.Context) error

	// Terminate terminates a workflow in execution, returning an error if applicable
	Terminate(ctx context.Context, reason string, details ...interface{}) error
}

// scheduleRun provides an internal implementation of a(n) ScheduleRunRun
type scheduleRun struct {
	client *exampleClient
	run    client.WorkflowRun
}

// ID returns the workflow ID
func (r *scheduleRun) ID() string {
	return r.run.GetID()
}

// Run returns the inner client.WorkflowRun
func (r *scheduleRun) Run() client.WorkflowRun {
	return r.run
}

// RunID returns the execution ID
func (r *scheduleRun) RunID() string {
	return r.run.GetRunID()
}

// Cancel requests cancellation of a workflow in execution, returning an error if applicable
func (r *scheduleRun) Cancel(ctx context.Context) error {
	return r.client.CancelWorkflow(ctx, r.ID(), r.RunID())
}

// Get blocks until the workflow is complete, returning the result if applicable
func (r *scheduleRun) Get(ctx context.Context) (*ScheduleOutput, error) {
	var resp ScheduleOutput
	if err := r.run.Get(ctx, &resp); err != nil {
		return nil, err
	}
	return &resp, nil
}

// Terminate terminates a workflow in execution, returning an error if applicable
func (r *scheduleRun) Terminate(ctx context.Context, reason string, details ...interface{}) error {
	return r.client.TerminateWorkflow(ctx, r.ID(), r.RunID(), reason, details...)
}

// Reference to generated workflow functions
var (
	// exampleRegistrationMutex is a mutex for registering example.schedule.v1.Example workflows
	exampleRegistrationMutex sync.Mutex
	// ScheduleFunction implements a "example.schedule.v1.Schedule" workflow
	ScheduleFunction func(workflow.Context, *ScheduleInput) (*ScheduleOutput, error)
)

// ExampleWorkflowFunctions describes a mockable dependency for inlining workflows within other workflows
type (
	// ExampleWorkflowFunctions describes a mockable dependency for inlining workflows within other workflows
	ExampleWorkflowFunctions interface {
		// Schedule executes a "example.schedule.v1.Schedule" workflow inline
		Schedule(workflow.Context, *ScheduleInput) (*ScheduleOutput, error)
	}
	// exampleWorkflowFunctions provides an internal ExampleWorkflowFunctions implementation
	exampleWorkflowFunctions struct{}
)

func NewExampleWorkflowFunctions() ExampleWorkflowFunctions {
	return &exampleWorkflowFunctions{}
}

// Schedule executes a "example.schedule.v1.Schedule" workflow inline
func (f *exampleWorkflowFunctions) Schedule(ctx workflow.Context, req *ScheduleInput) (*ScheduleOutput, error) {
	if ScheduleFunction == nil {
		return nil, errors.New("Schedule requires workflow registration via RegisterExampleWorkflows or RegisterScheduleWorkflow")
	}
	return ScheduleFunction(ctx, req)
}

// ExampleWorkflows provides methods for initializing new example.schedule.v1.Example workflow values
type ExampleWorkflows interface {
	// Schedule initializes a new a(n) ScheduleWorkflow implementation
	Schedule(ctx workflow.Context, input *ScheduleWorkflowInput) (ScheduleWorkflow, error)
}

// RegisterExampleWorkflows registers example.schedule.v1.Example workflows with the given worker
func RegisterExampleWorkflows(r worker.WorkflowRegistry, workflows ExampleWorkflows) {
	RegisterScheduleWorkflow(r, workflows.Schedule)
}

// RegisterScheduleWorkflow registers a example.schedule.v1.Example.Schedule workflow with the given worker
func RegisterScheduleWorkflow(r worker.WorkflowRegistry, wf func(workflow.Context, *ScheduleWorkflowInput) (ScheduleWorkflow, error)) {
	exampleRegistrationMutex.Lock()
	defer exampleRegistrationMutex.Unlock()
	ScheduleFunction = buildSchedule(wf)
	r.RegisterWorkflowWithOptions(ScheduleFunction, workflow.RegisterOptions{Name: ScheduleWorkflowName})
}

// buildSchedule converts a Schedule workflow struct into a valid workflow function
func buildSchedule(ctor func(workflow.Context, *ScheduleWorkflowInput) (ScheduleWorkflow, error)) func(workflow.Context, *ScheduleInput) (*ScheduleOutput, error) {
	return func(ctx workflow.Context, req *ScheduleInput) (*ScheduleOutput, error) {
		input := &ScheduleWorkflowInput{
			Req: req,
		}
		wf, err := ctor(ctx, input)
		if err != nil {
			return nil, err
		}
		if initializable, ok := wf.(helpers.Initializable); ok {
			if err := initializable.Initialize(ctx); err != nil {
				return nil, err
			}
		}
		return wf.Execute(ctx)
	}
}

// ScheduleWorkflowInput describes the input to a(n) example.schedule.v1.Schedule workflow constructor
type ScheduleWorkflowInput struct {
	Req *ScheduleInput
}

// ScheduleWorkflow describes a(n) example.schedule.v1.Schedule workflow implementation
type ScheduleWorkflow interface {
	// Execute defines the entrypoint to a(n) example.schedule.v1.Schedule workflow
	Execute(ctx workflow.Context) (*ScheduleOutput, error)
}

// ScheduleChild executes a child example.schedule.v1.Schedule workflow and blocks until error or response received
func ScheduleChild(ctx workflow.Context, req *ScheduleInput, options ...*ScheduleChildOptions) (*ScheduleOutput, error) {
	childRun, err := ScheduleChildAsync(ctx, req, options...)
	if err != nil {
		return nil, err
	}
	return childRun.Get(ctx)
}

// ScheduleChildAsync starts a child example.schedule.v1.Schedule workflow and returns a handle to the child workflow run
func ScheduleChildAsync(ctx workflow.Context, req *ScheduleInput, options ...*ScheduleChildOptions) (*ScheduleChildRun, error) {
	var o *ScheduleChildOptions
	if len(options) > 0 && options[0] != nil {
		o = options[0]
	} else {
		o = NewScheduleChildOptions()
	}
	opts, err := o.Build(ctx, req.ProtoReflect())
	if err != nil {
		return nil, fmt.Errorf("error initializing workflow.ChildWorkflowOptions: %w", err)
	}
	ctx = workflow.WithChildOptions(ctx, opts)
	if o.dc != nil {
		ctx = workflow.WithDataConverter(ctx, o.dc)
	}
	return &ScheduleChildRun{Future: workflow.ExecuteChildWorkflow(ctx, ScheduleWorkflowName, req)}, nil
}

// ScheduleChildOptions provides configuration for a child example.schedule.v1.Schedule workflow operation
type ScheduleChildOptions struct {
	options                  workflow.ChildWorkflowOptions
	executionTimeout         *time.Duration
	id                       *string
	idReusePolicy            enumsv1.WorkflowIdReusePolicy
	retryPolicy              *temporal.RetryPolicy
	runTimeout               *time.Duration
	searchAttributes         map[string]any
	taskQueue                *string
	taskTimeout              *time.Duration
	workflowIdConflictPolicy enumsv1.WorkflowIdConflictPolicy
	dc                       converter.DataConverter
	parentClosePolicy        enumsv1.ParentClosePolicy
	waitForCancellation      *bool
}

// NewScheduleChildOptions initializes a new ScheduleChildOptions value
func NewScheduleChildOptions() *ScheduleChildOptions {
	return &ScheduleChildOptions{}
}

// Build initializes a new go.temporal.io/sdk/workflow.ChildWorkflowOptions value with defaults and overrides applied
func (o *ScheduleChildOptions) Build(ctx workflow.Context, req protoreflect.Message) (workflow.ChildWorkflowOptions, error) {
	opts := o.options
	if v := o.id; v != nil {
		opts.WorkflowID = *v
	}
	if v := o.idReusePolicy; v != enumsv1.WORKFLOW_ID_REUSE_POLICY_UNSPECIFIED {
		opts.WorkflowIDReusePolicy = v
	}
	if v := o.taskQueue; v != nil {
		opts.TaskQueue = *v
	} else if opts.TaskQueue == "" {
		opts.TaskQueue = ExampleTaskQueue
	}
	if v := o.retryPolicy; v != nil {
		opts.RetryPolicy = v
	}
	if v := o.searchAttributes; v != nil {
		opts.SearchAttributes = o.searchAttributes
	}
	if v := o.executionTimeout; v != nil {
		opts.WorkflowExecutionTimeout = *v
	}
	if v := o.runTimeout; v != nil {
		opts.WorkflowRunTimeout = *v
	}
	if v := o.taskTimeout; v != nil {
		opts.WorkflowTaskTimeout = *v
	}
	if v := o.parentClosePolicy; v != enumsv1.PARENT_CLOSE_POLICY_UNSPECIFIED {
		opts.ParentClosePolicy = v
	}
	if v := o.waitForCancellation; v != nil {
		opts.WaitForCancellation = *v
	}
	return opts, nil
}

// WithChildWorkflowOptions sets the initial go.temporal.io/sdk/workflow.ChildWorkflowOptions
func (o *ScheduleChildOptions) WithChildWorkflowOptions(options workflow.ChildWorkflowOptions) *ScheduleChildOptions {
	o.options = options
	return o
}

// WithDataConverter registers a DataConverter for the child workflow
func (o *ScheduleChildOptions) WithDataConverter(dc converter.DataConverter) *ScheduleChildOptions {
	o.dc = dc
	return o
}

// WithExecutionTimeout sets the WorkflowExecutionTimeout value
func (o *ScheduleChildOptions) WithExecutionTimeout(d time.Duration) *ScheduleChildOptions {
	o.executionTimeout = &d
	return o
}

// WithID sets the WorkflowID value
func (o *ScheduleChildOptions) WithID(id string) *ScheduleChildOptions {
	o.id = &id
	return o
}

// WithIDReusePolicy sets the WorkflowIDReusePolicy value
func (o *ScheduleChildOptions) WithIDReusePolicy(policy enumsv1.WorkflowIdReusePolicy) *ScheduleChildOptions {
	o.idReusePolicy = policy
	return o
}

// WithParentClosePolicy sets the WorkflowIDReusePolicy value
func (o *ScheduleChildOptions) WithParentClosePolicy(policy enumsv1.ParentClosePolicy) *ScheduleChildOptions {
	o.parentClosePolicy = policy
	return o
}

// WithRetryPolicy sets the RetryPolicy value
func (o *ScheduleChildOptions) WithRetryPolicy(policy *temporal.RetryPolicy) *ScheduleChildOptions {
	o.retryPolicy = policy
	return o
}

// WithRunTimeout sets the WorkflowRunTimeout value
func (o *ScheduleChildOptions) WithRunTimeout(d time.Duration) *ScheduleChildOptions {
	o.runTimeout = &d
	return o
}

// WithSearchAttributes sets the SearchAttributes value
func (o *ScheduleChildOptions) WithSearchAttributes(sa map[string]any) *ScheduleChildOptions {
	o.searchAttributes = sa
	return o
}

// WithTaskTimeout sets the WorkflowTaskTimeout value
func (o *ScheduleChildOptions) WithTaskTimeout(d time.Duration) *ScheduleChildOptions {
	o.taskTimeout = &d
	return o
}

// WithTaskQueue sets the TaskQueue value
func (o *ScheduleChildOptions) WithTaskQueue(tq string) *ScheduleChildOptions {
	o.taskQueue = &tq
	return o
}

// WithWaitForCancellation sets the WaitForCancellation value
func (o *ScheduleChildOptions) WithWaitForCancellation(wait bool) *ScheduleChildOptions {
	o.waitForCancellation = &wait
	return o
}

// WithWorkflowIdConflictPolicy sets the WorkflowIdConflictPolicy value
func (o *ScheduleChildOptions) WithWorkflowIdConflictPolicy(policy enumsv1.WorkflowIdConflictPolicy) *ScheduleChildOptions {
	o.workflowIdConflictPolicy = policy
	return o
}

// ScheduleChildRun describes a child Schedule workflow run
type ScheduleChildRun struct {
	Future workflow.ChildWorkflowFuture
}

// Get blocks until the workflow is completed, returning the response value
func (r *ScheduleChildRun) Get(ctx workflow.Context) (*ScheduleOutput, error) {
	var resp ScheduleOutput
	if err := r.Future.Get(ctx, &resp); err != nil {
		return nil, err
	}
	return &resp, nil
}

// Select adds this completion to the selector. Callback can be nil.
func (r *ScheduleChildRun) Select(sel workflow.Selector, fn func(*ScheduleChildRun)) workflow.Selector {
	return sel.AddFuture(r.Future, func(workflow.Future) {
		if fn != nil {
			fn(r)
		}
	})
}

// SelectStart adds waiting for start to the selector. Callback can be nil.
func (r *ScheduleChildRun) SelectStart(sel workflow.Selector, fn func(*ScheduleChildRun)) workflow.Selector {
	return sel.AddFuture(r.Future.GetChildWorkflowExecution(), func(workflow.Future) {
		if fn != nil {
			fn(r)
		}
	})
}

// WaitStart waits for the child workflow to start
func (r *ScheduleChildRun) WaitStart(ctx workflow.Context) (*workflow.Execution, error) {
	var exec workflow.Execution
	if err := r.Future.GetChildWorkflowExecution().Get(ctx, &exec); err != nil {
		return nil, err
	}
	return &exec, nil
}

// ExampleActivities describes available worker activities
type ExampleActivities interface{}

// RegisterExampleActivities registers activities with a worker
func RegisterExampleActivities(r worker.ActivityRegistry, activities ExampleActivities) {}

// TestClient provides a testsuite-compatible Client
type TestExampleClient struct {
	env       *testsuite.TestWorkflowEnvironment
	workflows ExampleWorkflows
}

var _ ExampleClient = &TestExampleClient{}

// NewTestExampleClient initializes a new TestExampleClient value
func NewTestExampleClient(env *testsuite.TestWorkflowEnvironment, workflows ExampleWorkflows, activities ExampleActivities) *TestExampleClient {
	if workflows != nil {
		RegisterExampleWorkflows(env, workflows)
	}
	if activities != nil {
		RegisterExampleActivities(env, activities)
	}
	return &TestExampleClient{env, workflows}
}

// Schedule executes a(n) example.schedule.v1.Schedule workflow in the test environment
func (c *TestExampleClient) Schedule(ctx context.Context, req *ScheduleInput, opts ...*ScheduleOptions) (*ScheduleOutput, error) {
	run, err := c.ScheduleAsync(ctx, req, opts...)
	if err != nil {
		return nil, err
	}
	return run.Get(ctx)
}

// ScheduleAsync executes a(n) example.schedule.v1.Schedule workflow in the test environment
func (c *TestExampleClient) ScheduleAsync(ctx context.Context, req *ScheduleInput, options ...*ScheduleOptions) (ScheduleRun, error) {
	var o *ScheduleOptions
	if len(options) > 0 && options[0] != nil {
		o = options[0]
	} else {
		o = NewScheduleOptions()
	}
	opts, err := o.Build(req.ProtoReflect())
	if err != nil {
		return nil, fmt.Errorf("error initializing client.StartWorkflowOptions: %w", err)
	}
	return &testScheduleRun{client: c, env: c.env, opts: &opts, req: req, workflows: c.workflows}, nil
}

// GetSchedule is a noop
func (c *TestExampleClient) GetSchedule(ctx context.Context, workflowID string, runID string) ScheduleRun {
	return &testScheduleRun{env: c.env, workflows: c.workflows}
}

// CancelWorkflow requests cancellation of an existing workflow execution
func (c *TestExampleClient) CancelWorkflow(ctx context.Context, workflowID string, runID string) error {
	c.env.CancelWorkflow()
	return nil
}

// TerminateWorkflow terminates an existing workflow execution
func (c *TestExampleClient) TerminateWorkflow(ctx context.Context, workflowID string, runID string, reason string, details ...interface{}) error {
	return c.CancelWorkflow(ctx, workflowID, runID)
}

var _ ScheduleRun = &testScheduleRun{}

// testScheduleRun provides convenience methods for interacting with a(n) example.schedule.v1.Schedule workflow in the test environment
type testScheduleRun struct {
	client    *TestExampleClient
	env       *testsuite.TestWorkflowEnvironment
	isStarted atomic.Bool
	opts      *client.StartWorkflowOptions
	req       *ScheduleInput
	workflows ExampleWorkflows
}

// Cancel requests cancellation of a workflow in execution, returning an error if applicable
func (r *testScheduleRun) Cancel(ctx context.Context) error {
	return r.client.CancelWorkflow(ctx, r.ID(), r.RunID())
}

// Get retrieves a test example.schedule.v1.Schedule workflow result
func (r *testScheduleRun) Get(context.Context) (*ScheduleOutput, error) {
	if r.isStarted.CompareAndSwap(false, true) {
		r.env.ExecuteWorkflow(ScheduleWorkflowName, r.req)
	}
	if !r.env.IsWorkflowCompleted() {
		return nil, errors.New("workflow in progress")
	}
	if err := r.env.GetWorkflowError(); err != nil {
		return nil, err
	}
	var result ScheduleOutput
	if err := r.env.GetWorkflowResult(&result); err != nil {
		return nil, err
	}
	return &result, nil
}

// ID returns a test example.schedule.v1.Schedule workflow run's workflow ID
func (r *testScheduleRun) ID() string {
	if r.opts != nil {
		return r.opts.ID
	}
	return ""
}

// Run noop implementation
func (r *testScheduleRun) Run() client.WorkflowRun {
	return nil
}

// RunID noop implementation
func (r *testScheduleRun) RunID() string {
	return ""
}

// Terminate terminates a workflow in execution, returning an error if applicable
func (r *testScheduleRun) Terminate(ctx context.Context, reason string, details ...interface{}) error {
	return r.client.TerminateWorkflow(ctx, r.ID(), r.RunID(), reason, details...)
}

// ExampleCliOptions describes runtime configuration for example.schedule.v1.Example cli
type ExampleCliOptions struct {
	after            func(*v2.Context) error
	before           func(*v2.Context) error
	clientForCommand func(*v2.Context) (client.Client, error)
	worker           func(*v2.Context, client.Client) (worker.Worker, error)
}

// NewExampleCliOptions initializes a new ExampleCliOptions value
func NewExampleCliOptions() *ExampleCliOptions {
	return &ExampleCliOptions{}
}

// WithAfter injects a custom After hook to be run after any command invocation
func (opts *ExampleCliOptions) WithAfter(fn func(*v2.Context) error) *ExampleCliOptions {
	opts.after = fn
	return opts
}

// WithBefore injects a custom Before hook to be run prior to any command invocation
func (opts *ExampleCliOptions) WithBefore(fn func(*v2.Context) error) *ExampleCliOptions {
	opts.before = fn
	return opts
}

// WithClient provides a Temporal client factory for use by commands
func (opts *ExampleCliOptions) WithClient(fn func(*v2.Context) (client.Client, error)) *ExampleCliOptions {
	opts.clientForCommand = fn
	return opts
}

// WithWorker provides an method for initializing a worker
func (opts *ExampleCliOptions) WithWorker(fn func(*v2.Context, client.Client) (worker.Worker, error)) *ExampleCliOptions {
	opts.worker = fn
	return opts
}

// NewExampleCli initializes a cli for a(n) example.schedule.v1.Example service
func NewExampleCli(options ...*ExampleCliOptions) (*v2.App, error) {
	commands, err := newExampleCommands(options...)
	if err != nil {
		return nil, fmt.Errorf("error initializing subcommands: %w", err)
	}
	return &v2.App{
		Name:                      "example",
		Commands:                  commands,
		DisableSliceFlagSeparator: true,
	}, nil
}

// NewExampleCliCommand initializes a cli command for a example.schedule.v1.Example service with subcommands for each query, signal, update, and workflow
func NewExampleCliCommand(options ...*ExampleCliOptions) (*v2.Command, error) {
	subcommands, err := newExampleCommands(options...)
	if err != nil {
		return nil, fmt.Errorf("error initializing subcommands: %w", err)
	}
	return &v2.Command{
		Name:        "example",
		Subcommands: subcommands,
	}, nil
}

// newExampleCommands initializes (sub)commands for a example.schedule.v1.Example cli or command
func newExampleCommands(options ...*ExampleCliOptions) ([]*v2.Command, error) {
	opts := &ExampleCliOptions{}
	if len(options) > 0 {
		opts = options[0]
	}
	if opts.clientForCommand == nil {
		opts.clientForCommand = func(*v2.Context) (client.Client, error) {
			return client.Dial(client.Options{})
		}
	}
	commands := []*v2.Command{
		{
			Name:                   "schedule",
			Usage:                  "executes a(n) example.schedule.v1.Schedule workflow",
			Category:               "WORKFLOWS",
			UseShortOptionHandling: true,
			Before:                 opts.before,
			After:                  opts.after,
			Flags: []v2.Flag{
				&v2.BoolFlag{
					Name:    "detach",
					Usage:   "run workflow in the background and print workflow and execution id",
					Aliases: []string{"d"},
				},
				&v2.StringFlag{
					Name:    "task-queue",
					Usage:   "task queue name",
					Aliases: []string{"t"},
					EnvVars: []string{"TEMPORAL_TASK_QUEUE_NAME", "TEMPORAL_TASK_QUEUE", "TASK_QUEUE_NAME", "TASK_QUEUE"},
					Value:   "schedule-v1",
				},
				&v2.StringFlag{
					Name:     "input-file",
					Usage:    "path to json-formatted input file",
					Aliases:  []string{"f"},
					Category: "INPUT",
				},
			},
			Action: func(cmd *v2.Context) error {
				tc, err := opts.clientForCommand(cmd)
				if err != nil {
					return fmt.Errorf("error initializing client for command: %w", err)
				}
				defer tc.Close()
				c := NewExampleClient(tc)
				req, err := UnmarshalCliFlagsToScheduleInput(cmd, helpers.UnmarshalCliFlagsOptions{FromFile: "input-file"})
				if err != nil {
					return fmt.Errorf("error unmarshalling request: %w", err)
				}
				opts := client.StartWorkflowOptions{}
				if tq := cmd.String("task-queue"); tq != "" {
					opts.TaskQueue = tq
				}
				run, err := c.ScheduleAsync(cmd.Context, req, NewScheduleOptions().WithStartWorkflowOptions(opts))
				if err != nil {
					return fmt.Errorf("error starting %s workflow: %w", ScheduleWorkflowName, err)
				}
				if cmd.Bool("detach") {
					fmt.Println("success")
					fmt.Printf("workflow id: %s\n", run.ID())
					fmt.Printf("run id: %s\n", run.RunID())
					return nil
				}
				if resp, err := run.Get(cmd.Context); err != nil {
					return err
				} else {
					b, err := protojson.Marshal(resp)
					if err != nil {
						return fmt.Errorf("error serializing response json: %w", err)
					}
					var out bytes.Buffer
					if err := json.Indent(&out, b, "", "  "); err != nil {
						return fmt.Errorf("error formatting json: %w", err)
					}
					fmt.Println(out.String())
					return nil
				}
			},
		},
	}
	if opts.worker != nil {
		commands = append(commands, []*v2.Command{
			{
				Name:                   "worker",
				Usage:                  "runs a example.schedule.v1.Example worker process",
				UseShortOptionHandling: true,
				Before:                 opts.before,
				After:                  opts.after,
				Action: func(cmd *v2.Context) error {
					c, err := opts.clientForCommand(cmd)
					if err != nil {
						return fmt.Errorf("error initializing client for command: %w", err)
					}
					defer c.Close()
					w, err := opts.worker(cmd, c)
					if opts.worker != nil {
						if err != nil {
							return fmt.Errorf("error initializing worker: %w", err)
						}
					}
					if err := w.Start(); err != nil {
						return fmt.Errorf("error starting worker: %w", err)
					}
					defer w.Stop()
					<-cmd.Context.Done()
					return nil
				},
			},
		}...)
	}
	sort.Slice(commands, func(i, j int) bool {
		return commands[i].Name < commands[j].Name
	})
	return commands, nil
}

// UnmarshalCliFlagsToScheduleInput unmarshals a ScheduleInput from command line flags
func UnmarshalCliFlagsToScheduleInput(cmd *v2.Context, options ...helpers.UnmarshalCliFlagsOptions) (*ScheduleInput, error) {
	opts := helpers.FlattenUnmarshalCliFlagsOptions(options...)
	var result ScheduleInput
	if opts.FromFile != "" && cmd.IsSet(opts.FromFile) {
		f, err := gohomedir.Expand(cmd.String(opts.FromFile))
		if err != nil {
			f = cmd.String(opts.FromFile)
		}
		b, err := os.ReadFile(f)
		if err != nil {
			return nil, fmt.Errorf("error reading %s: %w", opts.FromFile, err)
		}
		if err := protojson.Unmarshal(b, &result); err != nil {
			return nil, fmt.Errorf("error parsing %s json: %w", opts.FromFile, err)
		}
	}
	return &result, nil
}

// WithExampleSchemeTypes registers all Example protobuf types with the given scheme
func WithExampleSchemeTypes() scheme.Option {
	return func(s *scheme.Scheme) {
		s.RegisterType(File_example_schedule_v1_schedule_proto.Messages().ByName("ScheduleInput"))
		s.RegisterType(File_example_schedule_v1_schedule_proto.Messages().ByName("ScheduleOutput"))
	}
}
