package runner

import (
	"strings"

	"github.com/easyai/easyai-ai-gateway/apps/api/internal/config"
	"github.com/easyai/easyai-ai-gateway/apps/api/internal/store"
)

type directOSSUploader struct {
	endpoint        string
	bucket          string
	accessKeyID     string
	accessKeySecret string
	publicBaseURL   string
	objectPrefix    string
}

func newDirectOSSUploader(cfg config.Config) *directOSSUploader {
	if !cfg.MediaOSSDirectEnabled {
		return nil
	}
	return &directOSSUploader{
		endpoint:        strings.TrimRight(cfg.MediaOSSEndpoint, "/"),
		bucket:          strings.TrimSpace(cfg.MediaOSSBucket),
		accessKeyID:     strings.TrimSpace(cfg.MediaOSSAccessKeyID),
		accessKeySecret: strings.TrimSpace(cfg.MediaOSSAccessKeySecret),
		publicBaseURL:   strings.TrimRight(cfg.MediaOSSPublicBaseURL, "/"),
		objectPrefix:    strings.Trim(cfg.MediaOSSObjectPrefix, "/"),
	}
}

func directOSSScene(scene string) bool {
	switch strings.TrimSpace(scene) {
	case store.FileStorageSceneUpload, store.FileStorageSceneRequestAsset, store.FileStorageSceneImageResult:
		return true
	default:
		return false
	}
}

func (u *directOSSUploader) fileStorageChannel() store.FileStorageChannel {
	if u == nil {
		return store.FileStorageChannel{}
	}
	return store.FileStorageChannel{
		ChannelKey:      "environment-direct-oss",
		Name:            "Environment Direct OSS",
		Provider:        "aliyun_oss",
		AccessKeyID:     u.accessKeyID,
		AccessKeySecret: u.accessKeySecret,
		Priority:        10,
		Status:          "enabled",
		Scenes:          []string{store.FileStorageSceneUpload, store.FileStorageSceneRequestAsset, store.FileStorageSceneImageResult},
		Config: map[string]any{
			"endpoint":      u.endpoint,
			"bucket":        u.bucket,
			"publicBaseUrl": u.publicBaseURL,
			"objectPrefix":  u.objectPrefix,
		},
		RetryPolicy: map[string]any{
			"enabled":        true,
			"maxRetries":     2,
			"backoffSeconds": []any{0.25, 1.0},
		},
	}
}
