package autoprof

import (
	"context"
	"time"

	"github.com/aws/aws-sdk-go/service/s3/s3iface"
	"go.uber.org/zap"

	"code.justin.tv/video/autoprof/profs3"

	"code.justin.tv/eventbus/controlplane/internal/logger"
)

const repeatErrorThreshold = 1 * time.Hour

func Start(s3Client s3iface.S3API, bucketName string, l *logger.Logger) {
	go func() {
		var lastErrAt time.Time
		for {
			c := &profs3.Collector{
				S3:       s3Client,
				S3Bucket: bucketName,
				OnError: func(err error) error {
					return err
				},
			}
			if err := c.Run(context.Background()); err != nil {
				if time.Since(lastErrAt) < repeatErrorThreshold {
					l.Error("autoprof error, stopping profiling", zap.Error(err))
					break
				} else {
					l.Warn("autoprof error, restarting profiling", zap.Error(err))
					lastErrAt = time.Now()
				}
			}
		}
	}()
}
