package tioperator

import (
	"context"
	"fmt"
	"strings"

	"github.com/pingcap/tidb-operator/api/v2/core/v1alpha1"
	"github.com/samber/lo"
	apiv1 "github.com/tidbcloud/cluster-service-ng/api/cluster-service-ng/v1beta"
	"github.com/tidbcloud/cluster-service-ng/domain/entity"
	schemav1 "github.com/tidbcloud/cluster-service-ng/pkg/storage/etcd/schema/v1"
	"github.com/tidbcloud/tiinf/monitor/tilog"
	"go.uber.org/zap"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"
	corev1 "k8s.io/api/core/v1"
	apierrors "k8s.io/apimachinery/pkg/api/errors"
	"k8s.io/apimachinery/pkg/types"
	"sigs.k8s.io/controller-runtime/pkg/client"
)

func ListResourceManagerGroups(ctx context.Context, remoteCli client.Client, clusterId string) ([]*entity.Component, error) {
	return listResourceManagerGroups(ctx, remoteCli, dataplaneNamespace(clusterId))
}

func GetResourceManagerGroup(ctx context.Context, remoteCli client.Client, clusterId, groupId string) (*entity.Component, error) {
	resourceManagerGroupCr, err := getResourceManagerGroupCR(ctx, remoteCli, dataplaneNamespace(clusterId), groupId)
	if err != nil {
		if apierrors.IsNotFound(err) {
			return nil, status.Errorf(codes.NotFound, "resource manager group %s not found: %s", groupId, err)
		}
		return nil, status.Errorf(codes.Internal, "failed to get resource manager group %s: %s", groupId, err)
	}

	return cvtResourceManagerComponentToEn(ctx, resourceManagerGroupCr)
}

func UpdateResourceManagerGroup(ctx context.Context, remoteCli client.Client, clusterId, groupId string, options []UpdateOption) (*entity.Component, error) {
	resourceManagerGroupCr, err := getResourceManagerGroupCR(ctx, remoteCli, dataplaneNamespace(clusterId), groupId)
	if err != nil {
		if apierrors.IsNotFound(err) {
			return nil, status.Errorf(codes.NotFound, "resource manager group %s not found: %s", groupId, err)
		}
		return nil, status.Errorf(codes.Internal, "failed to get resource manager group %s: %s", groupId, err)
	}

	needUpdate, err := getUpdateExpectedResourceManagerGroup(ctx, resourceManagerGroupCr, options...)
	if err != nil {
		return nil, fmt.Errorf("failed to get expected resource manager group %s: %w", groupId, err)
	}

	if needUpdate {
		if err := remoteCli.Update(ctx, resourceManagerGroupCr); err != nil {
			return nil, status.Errorf(codes.Internal, "failed to update resource manager group cr %s: %s", groupId, err)
		}
	}

	return cvtResourceManagerComponentToEn(ctx, resourceManagerGroupCr)
}

func getResourceManagerGroupCR(ctx context.Context, remoteCli client.Client, dataplaneNs, groupId string) (*v1alpha1.ResourceManagerGroup, error) {
	if !strings.HasPrefix(groupId, componentGroupPrefix) {
		groupId = fmt.Sprintf("%s%s", componentGroupPrefix, groupId)
	}

	// get resource manager group
	var resourceManagerGroup v1alpha1.ResourceManagerGroup
	key := types.NamespacedName{Name: groupId, Namespace: dataplaneNs}

	if err := remoteCli.Get(
		ctx, key, &resourceManagerGroup,
	); err != nil {
		return nil, err
	}

	return &resourceManagerGroup, nil
}

func listResourceManagerGroups(ctx context.Context, remoteClient client.Client, dataplaneNs string) ([]*entity.Component, error) {
	// get all component groups
	var resourceManagerGroups v1alpha1.ResourceManagerGroupList
	if err := remoteClient.List(ctx, &resourceManagerGroups, client.InNamespace(dataplaneNs)); err != nil {
		return nil, status.Errorf(codes.Internal, "failed to list resource manager groups: %s", err)
	}

	resourceManagerComponents := make([]*entity.Component, 0, len(resourceManagerGroups.Items))

	for i := range resourceManagerGroups.Items {
		compEn, err := cvtResourceManagerComponentToEn(ctx, &resourceManagerGroups.Items[i])

		if err != nil {
			tilog.Warn(ctx, "convert resource manager group to component", zap.Error(err))
		} else {
			resourceManagerComponents = append(resourceManagerComponents, compEn)
		}
	}
	return resourceManagerComponents, nil
}

func cvtResourceManagerComponentToEn(ctx context.Context, resourceManagerGroup *v1alpha1.ResourceManagerGroup) (*entity.Component, error) {
	compEn := &entity.Component{
		Id:            strings.Split(resourceManagerGroup.Name, "-")[1], // db-<Id>
		ComponentType: apiv1.ComponentType_RESOURCE_MANAGER,
	}
	setTemplateVersionFromAnnotations(compEn, resourceManagerGroup.Annotations)

	var err error
	// find the resource manager container
	var resourceManagerContainer corev1.Container
	foundContainer := false
	if resourceManagerGroup.Spec.Template.Spec.Overlay != nil &&
		resourceManagerGroup.Spec.Template.Spec.Overlay.Pod != nil {
		for i := range resourceManagerGroup.Spec.Template.Spec.Overlay.Pod.Spec.Containers {
			if resourceManagerGroup.Spec.Template.Spec.Overlay.Pod.Spec.Containers[i].Name == "resource-manager" {
				resourceManagerContainer = resourceManagerGroup.Spec.Template.Spec.Overlay.Pod.Spec.Containers[i]
				foundContainer = true
				break
			}
		}
	}
	if !foundContainer {
		return nil, fmt.Errorf("container named 'resource-manager' not found in ResourceManagerGroup %s", resourceManagerGroup.Name)
	}

	// Get nodeSelector from Overlay if present
	var nodeSelector map[string]string
	if resourceManagerGroup.Spec.Template.Spec.Overlay != nil &&
		resourceManagerGroup.Spec.Template.Spec.Overlay.Pod != nil {
		nodeSelector = resourceManagerGroup.Spec.Template.Spec.Overlay.Pod.Spec.NodeSelector
	}

	compEn.NodeQuota, err = CvtNodeSpecToQuota(
		resourceManagerGroup.Labels,
		resourceManagerGroup.Annotations,
		uint32(*resourceManagerGroup.Spec.Replicas),
		resourceManagerContainer.Resources.Limits,
		nodeSelector,
	)
	if err != nil {
		return nil, fmt.Errorf("failed to get resource manager group %s quota: %w", compEn.GetId(), err)
	}
	compEn.Version = resourceManagerGroup.Spec.Template.Spec.Version
	imageRepo, imageTag := splitImageRepoTag(resourceManagerGroup.Spec.Template.Spec.Image)
	compEn.Configuration = &entity.ComponentConfiguration{
		ImageRepo:                imageRepo,
		ImageTag:                 imageTag,
		ConfigurationFileContent: string(resourceManagerGroup.Spec.Template.Spec.Config),
	}

	compEn.Storages, err = cvtStoragesToEn(ctx, resourceManagerGroup.Spec.Template.Spec.Volumes)
	if err != nil {
		return nil, err
	}
	compEn.Phase = getResourceManagerGroupStatus(ctx, resourceManagerGroup)

	return compEn, nil
}

func getResourceManagerGroupStatus(ctx context.Context, resourceManagerGroup *v1alpha1.ResourceManagerGroup) apiv1.Component_Phase {
	if !isSynced(resourceManagerGroup.Status.Conditions) {
		tilog.Warn(ctx, "resourceManagerGroup is not synced", zap.Any("Conditions", resourceManagerGroup.Status.Conditions))
		return apiv1.Component_MODIFYING
	}

	if !isUpToDate(resourceManagerGroup.Generation, resourceManagerGroup.Status.CommonStatus) {
		tilog.Warn(ctx, "resourceManagerGroup is not up to date", zap.Any("Status", resourceManagerGroup.Status))
		return apiv1.Component_MODIFYING
	}

	// check if resourceManagerGroup is ready
	if !isReady(resourceManagerGroup.Status.Conditions) {
		tilog.Warn(ctx, "resourceManagerGroup is not ready", zap.Any("Conditions", resourceManagerGroup.Status.Conditions))
		return apiv1.Component_UNAVAILABLE
	}

	if resourceManagerGroup.Status.ReadyReplicas == 0 || resourceManagerGroup.Status.UpdatedReplicas == 0 {
		tilog.Warn(ctx, "resourceManagerGroup has zero ready or updated replicas", zap.Int32("ReadyReplicas", resourceManagerGroup.Status.ReadyReplicas), zap.Int32("UpdatedReplicas", resourceManagerGroup.Status.UpdatedReplicas))
		return apiv1.Component_UNAVAILABLE
	}

	return apiv1.Component_AVAILABLE
}

func getUpdateExpectedResourceManagerGroup(ctx context.Context, resourceManagerGroupCr *v1alpha1.ResourceManagerGroup, options ...UpdateOption) (bool, error) {
	var needUpdate bool
	for _, opt := range options {
		switch opt.Option {
		case OpsUpdateNodeCount:
			count, ok := opt.Value.(uint32)
			if !ok {
				tilog.Error(ctx, "invalid node count", zap.Any("value", opt.Value))
				return false, fmt.Errorf("invalid node count for resource manager group %s", resourceManagerGroupCr.Name)
			}
			if count > 0 {
				currNodeQuota, err := CvtNodeSpecToQuota(resourceManagerGroupCr.Labels, resourceManagerGroupCr.Annotations, uint32(*resourceManagerGroupCr.Spec.Replicas), nil, nil)
				if err != nil {
					return false, status.Errorf(codes.Internal, "failed to convert node spec to quota for resource manager group %s: %s", resourceManagerGroupCr.Name, err)
				}

				nodeQuota := &entity.NodeQuota{
					NodeCount: count,
				}

				err = checkNodeQuota(currNodeQuota, nodeQuota)
				if err != nil {
					return false, status.Errorf(codes.InvalidArgument, "invalid node quota for resource manager group %s: %s", resourceManagerGroupCr.Name, err)
				}

				if uint32(*resourceManagerGroupCr.Spec.Replicas) != count {
					resourceManagerGroupCr.Spec.Replicas = lo.ToPtr(int32(count))
					needUpdate = true
				}
			}

		case OpsUpdateNodeSpec:
			nodeSpec, ok := opt.Value.(*entity.NodeSpec)
			if !ok {
				tilog.Error(ctx, "invalid node spec", zap.Any("value", opt.Value))
				return false, fmt.Errorf("invalid node spec for resource manager group %s", resourceManagerGroupCr.Name)
			}

			resourceRequirements, err := setNodeSpec(nodeSpec, resourceManagerGroupCr.Labels, resourceManagerGroupCr.Spec.Template.Spec.Overlay.Pod.Spec.NodeSelector, apiv1.ComponentType_RESOURCE_MANAGER)
			if err != nil {
				tilog.Error(ctx, "set node spec", zap.Error(err))
				return false, fmt.Errorf("failed to set node spec for resource manager group %s: %w", resourceManagerGroupCr.Name, err)
			}
			for i := range resourceManagerGroupCr.Spec.Template.Spec.Overlay.Pod.Spec.Containers {
				if resourceManagerGroupCr.Spec.Template.Spec.Overlay.Pod.Spec.Containers[i].Name == "resource-manager" {
					resourceManagerGroupCr.Spec.Template.Spec.Overlay.Pod.Spec.Containers[i].Resources = resourceRequirements

					needUpdate = true
					break
				}
			}
		case OpsUpdateMaxCount:
			maxCount, ok := opt.Value.(uint32)
			if !ok {
				tilog.Error(ctx, "invalid max count", zap.Any("value", opt.Value))
				return false, fmt.Errorf("invalid max count for resource manager group %s", resourceManagerGroupCr.Name)
			}
			if maxCount > 0 {
				annotations := resourceManagerGroupCr.Annotations
				if annotations == nil {
					annotations = map[string]string{}
				}

				annotations[schemav1.AnnotationsComponentMaxCount] = fmt.Sprintf("%d", maxCount)
				resourceManagerGroupCr.Annotations = annotations

				needUpdate = true
			}
		case OpsUpdateMinCount:
			minCount, ok := opt.Value.(uint32)
			if !ok {
				tilog.Error(ctx, "invalid min count", zap.Any("value", opt.Value))
			}

			annotations := resourceManagerGroupCr.Annotations
			if annotations == nil {
				annotations = map[string]string{}
			}

			annotations[schemav1.AnnotationsComponentMinCount] = fmt.Sprintf("%d", minCount)
			resourceManagerGroupCr.Annotations = annotations

			needUpdate = true
		case OpsUpdateVersion:
			version, ok := opt.Value.(string)
			if !ok {
				tilog.Error(ctx, "invalid version", zap.Any("value", opt.Value))
				return false, fmt.Errorf("invalid version for resource manager group %s", resourceManagerGroupCr.Name)
			}
			if version != "" {
				resourceManagerGroupCr.Spec.Template.Spec.Version = version
				needUpdate = true
			}
		case OpsUpdateImage:
			image, ok := opt.Value.(string)
			if !ok {
				tilog.Error(ctx, "invalid image", zap.Any("value", opt.Value))
				return false, fmt.Errorf("invalid image for resource manager group %s", resourceManagerGroupCr.Name)
			}
			if image != "" {
				resourceManagerGroupCr.Spec.Template.Spec.Image = &image
				needUpdate = true
			}
		case OpsUpdateConfig:
			config, ok := opt.Value.(string)
			if !ok {
				tilog.Error(ctx, "invalid config", zap.Any("value", opt.Value))
				return false, fmt.Errorf("invalid config for resource manager group %s", resourceManagerGroupCr.Name)
			}
			if config != "" {
				resourceManagerGroupCr.Spec.Template.Spec.Config = v1alpha1.ConfigFile(config)
				needUpdate = true
			}
		case OpsUpdateUpdateStrategy:
			strategy, ok := opt.Value.(v1alpha1.ConfigUpdateStrategy)
			if !ok {
				tilog.Error(ctx, "invalid update strategy", zap.Any("value", opt.Value))
				return false, fmt.Errorf("invalid update strategy for resource manager group %s", resourceManagerGroupCr.Name)
			}
			if strategy != "" {
				resourceManagerGroupCr.Spec.Template.Spec.UpdateStrategy.Config = strategy
				needUpdate = true
			}
		case OpsUpdateNodeVersion:
			nodeVersion, ok := opt.Value.(string)
			if !ok || nodeVersion == "" {
				tilog.Error(ctx, "invalid node version", zap.Any("value", opt.Value))
				return false, status.Errorf(codes.InvalidArgument, "invalid node version for resource manager group %s", resourceManagerGroupCr.Name)
			}
			nodeSelector := resourceManagerGroupCr.Spec.Template.Spec.Overlay.Pod.Spec.NodeSelector
			if nodeSelector == nil {
				nodeSelector = map[string]string{}
			}
			if nodeSelector[schemav1.K8sVersionLabelKey] != nodeVersion {
				nodeSelector[schemav1.K8sVersionLabelKey] = nodeVersion
				resourceManagerGroupCr.Spec.Template.Spec.Overlay.Pod.Spec.NodeSelector = nodeSelector
				needUpdate = true
			}
		}
	}

	return needUpdate, nil
}
