package server

import (
	"context"
	"fmt"

	apiv1 "github.com/tidbcloud/cluster-service-ng/api/cluster-service-ng/v1beta"
	"github.com/tidbcloud/cluster-service-ng/domain/entity"
	"github.com/tidbcloud/cluster-service-ng/domain/workflow"
	"github.com/tidbcloud/cluster-service-ng/domain/workflow/dag"
	"github.com/tidbcloud/cluster-service-ng/pkg/runtime/actions"
	"github.com/tidbcloud/cluster-service-ng/pkg/tioperator"
	"github.com/tidbcloud/cluster-service-ng/pkg/utils"
	"github.com/tidbcloud/tiinf/monitor/tilog"
	"go.uber.org/zap"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"
	"google.golang.org/protobuf/encoding/protojson"
)

func (s *serverImpl) SetSharedPoolComponentQuota(ctx context.Context, sharedPoolId string, targetComponent *entity.Component) (*entity.Component, error) {
	if sharedPoolId == "" {
		return nil, status.Errorf(codes.InvalidArgument, "sharedPool id is required")
	}

	if targetComponent == nil {
		return nil, status.Errorf(codes.InvalidArgument, "target components is empty")
	}

	if targetComponent.GetComponentType() == apiv1.ComponentType_COMPONENT_TYPE_UNSPECIFIED {
		return nil, status.Errorf(codes.InvalidArgument, "target component type is required")
	}

	var currComponent *entity.Component

	var dagExecId string
	var dagSubmitted bool
	if err := s.transactioner.Transaction(ctx, func(ctx context.Context) error {
		// check if the sharedPool is locked
		unlockFunc, err := s.lock(ctx, sharedPoolId)
		if err != nil {
			tilog.Error(ctx, "failed to lock sharedPool", zap.String("sharedPoolId", sharedPoolId), zap.Error(err))
			return err
		}
		defer func() {
			if err := unlockFunc(); err != nil {
				tilog.Error(ctx, "failed to unlock sharedPool", zap.String("sharedPoolId", sharedPoolId), zap.Error(err))
			}
		}()

		// get shared first
		sharedPool, err := s.sharedPoolRepo.Load(ctx, sharedPoolId, false)
		if err != nil {
			if status.Code(err) != codes.NotFound {
				return status.Errorf(codes.Internal, "failed to load sharedPool: %s", err)
			}
			// not found, check if it's in creating
			return status.Errorf(codes.NotFound, "sharedPool %s not found", sharedPoolId)
		}
		if err := guardSharedPoolMutation(sharedPool, sharedPoolMutationBlockedWhilePaused); err != nil {
			return err
		}

		// merge sharedPool status from dag task
		err = s.mergeSharedPoolStatusFromDagTask(ctx, sharedPool)
		if err != nil {
			return status.Errorf(codes.Internal, "failed to merge sharedPool status from dag task: %s", err)
		}

		if sharedPool.GetPhase() == apiv1.SharedPool_CREATING {
			return status.Errorf(codes.FailedPrecondition, "shared pool is creating, please try again later")
		}

		if isTiKVRemoteWorkerGuardedComponentType(targetComponent.GetComponentType()) {
			if err := s.guardTiKVRemoteWorkersTopologyStable(ctx, sharedPool); err != nil {
				return err
			}
		}

		if targetComponent.GetId() == "" {
			tilog.Warn(ctx, "target component id is empty, will use default id")
			targetComponent.Id = sharedPool.GetDefaultComponenId()
		}

		if targetComponent.GetNodeQuota() == nil {
			return status.Errorf(codes.InvalidArgument, "target component node quota is required")
		}

		if targetComponent.GetNodeQuota().GetMaxNodeCount() == 0 {
			return status.Errorf(codes.InvalidArgument, "target component max node count is required")
		}

		if targetComponent.GetNodeQuota().GetMinNodeCount() == 0 {
			if targetComponent.GetComponentType() == apiv1.ComponentType_TIFLASH_COMPUTE ||
				targetComponent.GetComponentType() == apiv1.ComponentType_TIFLASH_WRITE {
				// tiflash min node count can be 0
				tilog.Warn(ctx, "target tiflash component min node count is 0, set to 0")
				targetComponent.GetNodeQuota().MinNodeCount = 0
			} else {
				// other components min node count cannot be 0
				return status.Errorf(codes.InvalidArgument, "target component min node count is required")
			}
		}

		if targetComponent.GetNodeQuota().GetMinNodeCount() > targetComponent.GetNodeQuota().GetMaxNodeCount() {
			return status.Errorf(codes.InvalidArgument, "target component min node count cannot be greater than max node count")
		}

		found := false
		for _, comp := range sharedPool.GetComponentGroups() {
			if comp.GetId() != targetComponent.GetId() || comp.GetComponentType() != targetComponent.GetComponentType() {
				continue
			}

			found = true
			currComponent = comp
			if err := checkComponentDeleteFence(comp); err != nil {
				return err
			}
			// found the target component
			if comp.GetNodeQuota().GetNodeCount() > targetComponent.GetNodeQuota().GetMaxNodeCount() {
				return status.Errorf(codes.InvalidArgument, "target component node count %d is greater than new max node count %d",
					comp.GetNodeQuota().GetNodeCount(), targetComponent.GetNodeQuota().GetMaxNodeCount())
			}

			if comp.GetNodeQuota().GetNodeCount() < targetComponent.GetNodeQuota().GetMinNodeCount() {
				tilog.Warn(ctx, "target component current node count is less than new min node count, need munal scale up",
					zap.String("componentId", comp.GetId()),
					zap.Uint32("currentNodeCount", comp.GetNodeQuota().GetNodeCount()),
					zap.Uint32("newMinNodeCount", targetComponent.GetNodeQuota().GetMinNodeCount()))
			}

			comp.GetNodeQuota().MaxNodeCount = targetComponent.GetNodeQuota().GetMaxNodeCount()
			comp.GetNodeQuota().MinNodeCount = targetComponent.GetNodeQuota().GetMinNodeCount()
			comp.Phase = apiv1.Component_MODIFYING
			break
		}

		if !found {
			return status.Errorf(codes.NotFound, "component %s %s not found in shared pool %s",
				entity.GetComponentTypeName(targetComponent), targetComponent.GetId(), sharedPool.GetId())
		}

		sharedPoolStr, err := protojson.Marshal(sharedPool)
		if err != nil {
			return status.Errorf(codes.Internal, "failed to marshal sharedPool: %s", err)
		}

		// start scale cluster dag
		args := actions.ActionArgs{
			workflow.SharedPoolIdKey:   actions.ActionArgString(sharedPool.GetId()),
			workflow.SharedPoolKey:     actions.ActionArgString(string(sharedPoolStr)),
			workflow.ComponentIdsKey:   actions.ActionArgString(targetComponent.GetId()), // only one component id
			workflow.ComponentTypesKey: actions.ActionArgString(entity.GetComponentTypeName(targetComponent)),
			entity.GetUpdateComponentKey(targetComponent): actions.ActionArgString(
				string(tioperator.OpsUpdateMaxCount) + "," + string(tioperator.OpsUpdateMinCount)),
			utils.TraceIdKey: utils.GetTraceId(ctx),
		}
		// FIXME: should use a patch style task, scale-component is a apply style task.
		dagExecId = utils.GeneratedDagExecId(ctx,
			fmt.Sprintf("set-component-node-quota-%s-%s-%s-%s",
				sharedPool.GetId(),
				entity.GetComponentTypeName(targetComponent),
				targetComponent.GetId(),
				utils.FnvHash(string(sharedPoolStr)),
			))
		err = s.dagExecutor.Submit(ctx, dag.PlanUpdateComponent, args, dagExecId)
		if err != nil {
			return status.Errorf(codes.Internal, "failed to submit set-component-node-quota dag: %s", err)
		}
		dagSubmitted = true
		return nil
	}); err != nil {
		if dagSubmitted {
			if abortErr := s.dagExecutor.Abort(ctx, dagExecId); abortErr != nil {
				tilog.Error(ctx, "failed to abort dag after transaction failure",
					zap.String("dagExecId", dagExecId),
					zap.Error(abortErr))
			}
		}
		return nil, err
	}

	return currComponent, nil
}
