package action

import (
	"fmt"

	dplanemgrv1 "github.com/tidbcloud/cluster-service-ng/api/dataplane-manager/v1"
	"github.com/tidbcloud/cluster-service-ng/domain/entity"
	"github.com/tidbcloud/cluster-service-ng/domain/workflow"
	"github.com/tidbcloud/cluster-service-ng/pkg/k8s"
	"github.com/tidbcloud/cluster-service-ng/pkg/runtime/actions"
	schemav1 "github.com/tidbcloud/cluster-service-ng/pkg/storage/etcd/schema/v1"
	"github.com/tidbcloud/cluster-service-ng/pkg/storage/mysql/schema"
	"github.com/tidbcloud/cluster-service-ng/pkg/storage/repo"
	"github.com/tidbcloud/cluster-service-ng/pkg/utils"
	o11yv2 "github.com/tidbcloud/observability/agent-control-server/api/v2"
	"github.com/tidbcloud/tiinf/monitor/tilog"
	"go.uber.org/zap"
	"sigs.k8s.io/controller-runtime/pkg/client"
)

const (
	CreateO11ySharedPoolAgentActionName = "create-o11y-sharedpool-agent"
)

type CreateO11ySharedPoolAgentAction struct {
	o11yBizType    string
	disableO11y    bool
	dpmgrClient    dplanemgrv1.DataPlaneServiceClient
	kubeClient     client.Client
	sharedPoolRepo repo.SharedPoolRepo
	agentNamespace string
}

func NewCreateO11ySharedPoolAgentAction(
	o11yBizType string,
	disableO11y bool,
	dpmgrClient dplanemgrv1.DataPlaneServiceClient,
	kubeClient client.Client,
	sharedPoolRepo repo.SharedPoolRepo,
	agentNamespace ...string,
) *CreateO11ySharedPoolAgentAction {
	return &CreateO11ySharedPoolAgentAction{
		o11yBizType:    o11yBizType,
		disableO11y:    disableO11y,
		dpmgrClient:    dpmgrClient,
		kubeClient:     kubeClient,
		sharedPoolRepo: sharedPoolRepo,
		agentNamespace: resolveO11yAgentNamespace(agentNamespace...),
	}
}

func (a *CreateO11ySharedPoolAgentAction) Name() string {
	return CreateO11ySharedPoolAgentActionName
}

// we do not check o11y agent status since it is not a core step
func (a *CreateO11ySharedPoolAgentAction) Invoke(args actions.ActionArgs) error {
	ctx := utils.GenerateContext(args)
	if a.disableO11y {
		tilog.Info(ctx, "o11y is disabled, skip create o11y sharedpool agent")
		return nil
	}
	tilog.Info(ctx, "create o11y sharedpool agent action invoked")
	sharedPoolId, err := args.GetString(workflow.SharedPoolIdKey)
	if err != nil {
		return fmt.Errorf("failed to get sharedpool id: %w", err)
	}
	dataplaneId, err := args.GetString(workflow.DataplaneIdKey)
	if err != nil {
		return fmt.Errorf("failed to get dataplane id: %w", err)
	}
	out, err := a.dpmgrClient.GetDataPlane(ctx, &dplanemgrv1.GetDataPlaneRequest{DataPlaneId: dataplaneId})
	if err != nil {
		tilog.Error(ctx, "failed to get dataplane", zap.String("dataplaneId", dataplaneId), zap.Error(err))
		return err
	}
	// From @mornyx
	// For biztype, hardcode it as <env>-tidbcloud-nextgen.
	// For tenant id, use <env>-tidbcloud-nextgen-dataplane.
	// Regarding tidbgroup: use the cluster ID as the application ID.
	// For sharedpool, use the formats sharedpool-<ID>.
	agent := new(o11yv2.SharedPoolAgent)
	agent.Name = sharedPoolId
	agent.Namespace = a.agentNamespace

	agent.Spec = o11yv2.SharedPoolAgentSpec{
		// FIXME(shenjun): use the real k8s cluster name from dataplane mgr
		KubernetesClusterName: out.GetKubernetes().GetName(),
		SharedPoolID:          sharedPoolId,
		O11y: o11yv2.O11yConfig{
			BizType:       a.o11yBizType,
			ApplicationID: sharedPoolId,
		},
	}
	if tenantId, _ := args.GetString(workflow.TenantIdKey); tenantId != "" {
		agent.Spec.O11y.TenantID = tenantId
	} else {
		agent.Spec.O11y.TenantID = schemav1.MultiTenantTag
	}

	sharedPool, err := a.sharedPoolRepo.Load(ctx, sharedPoolId, false)
	if err != nil {
		tilog.Warn(ctx, "failed to load shared pool, skip setting service-plan annotation", zap.String("sharedPoolId", sharedPoolId), zap.Error(err))
	} else if entity.HasSharedTiProxy(sharedPool) {
		if agent.Annotations == nil {
			agent.Annotations = make(map[string]string)
		}
		agent.Annotations["o11y.cloud.pingcap.com/tiproxy-deploy-type"] = schema.SharedPoolDeployTypeSharedTiProxy
	}

	if err := k8s.CreateIfNotExist(ctx, a.kubeClient, agent); err != nil {
		tilog.Error(ctx, "failed to create o11y sharedpool agent", zap.Error(err))
		return err
	}
	return nil
}
