package legacy

import (
	"fmt"

	o11yv1 "github.com/tidbcloud/observability/api/regionalserver/resourceworker/v1"
	"github.com/tidbcloud/observability/pkg/common/constants"
	taskpkg "github.com/tidbcloud/observability/pkg/resourceworker/controllers/integrationtask/v2/task"
)

// srcPrefix roots. These are paths WITHIN the source bucket; the bucket name
// must NOT be included. The ETL appends the per-cluster tail
// (<...>/logs/<category>/) according to deployType, so each tier only needs the
// prefix up to the point the ETL takes over.
const (
	// serverlessDataPrefixTmpl expands to 0/<bizType>/serverless; the ETL then
	// appends "-all-in-one/logs/<category>/".
	serverlessDataPrefixTmpl = "0/%s/serverless"
	// dedicatedDataPrefix is the data-generation root "0". The dedicated ETL
	// appends "/<tenantID>/<projectID>/<clusterID>/logs/<category>/" itself, so
	// the tenant ID must NOT be included here (doing so double-counts it).
	dedicatedDataPrefix = "0"
	// nextGenDataPrefix is the fixed root for next-gen clusters; the ETL appends
	// "/<applicationID>/logs/<category>/".
	nextGenDataPrefix = "0/next-gen"
)

// resolveDeployType classifies a bizType into the ETL deploy type. It delegates
// to task.DeployType so the classification has a single source of truth.
func resolveDeployType(bizType string) string {
	return taskpkg.DeployType(bizType)
}

// resolveSrcPrefix returns the ETL source prefix (a path within the source
// bucket) for this task, branching by tier to mirror the writer layout:
//   - serverless aggregates logs under 0/<bizType>/serverless/...
//   - next-gen keys logs under 0/next-gen/<applicationID>/logs/...
//   - dedicated keys logs by tenant at 0/<tenantID>/<projectID>/<clusterID>/logs/...
//
// The dedicated ETL builds the whole 0/<tenantID>/... tail itself from deployType,
// so its prefix is just the data-generation root "0".
func resolveSrcPrefix(it *o11yv1.IntegrationTask) string {
	bizType := it.Labels[constants.LabelBizType]
	switch resolveDeployType(bizType) {
	case taskpkg.DeployTypeServerless:
		return fmt.Sprintf(serverlessDataPrefixTmpl, bizType)
	case taskpkg.DeployTypePremium:
		return nextGenDataPrefix
	default:
		return dedicatedDataPrefix
	}
}
