package tioperator

import (
	"context"
	"fmt"
	"strings"
	"time"

	"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/api/resource"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/types"
	"sigs.k8s.io/controller-runtime/pkg/client"
)

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

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

func GetPDGroupCR(ctx context.Context, remoteCli client.Client, clusterId, groupId string) (*v1alpha1.PDGroup, error) {
	pdGroupCr, err := getPDGroupCR(ctx, remoteCli, dataplaneNamespace(clusterId), groupId)
	if err != nil {
		if apierrors.IsNotFound(err) {
			return nil, status.Errorf(codes.NotFound, "pd group %s not found: %s", groupId, err)
		}
		return nil, status.Errorf(codes.Internal, "failed to get pd group %s: %s", groupId, err)
	}
	return pdGroupCr, nil
}

func UpdatePDGroupMode(ctx context.Context, remoteCli client.Client, clusterId, groupId string, mode v1alpha1.PDMode) error {
	pdGroupCr, err := getPDGroupCR(ctx, remoteCli, dataplaneNamespace(clusterId), groupId)
	if err != nil {
		if apierrors.IsNotFound(err) {
			return status.Errorf(codes.NotFound, "pd group %s not found: %s", groupId, err)
		}
		return status.Errorf(codes.Internal, "failed to get pd group %s: %s", groupId, err)
	}
	if pdGroupCr.Spec.Template.Spec.Mode == mode {
		return nil
	}
	pdGroupCr.Spec.Template.Spec.Mode = mode
	if err := remoteCli.Update(ctx, pdGroupCr); err != nil {
		return status.Errorf(codes.Internal, "failed to update pd group cr %s mode: %s", groupId, err)
	}
	return nil
}

func PDModeToAPI(mode v1alpha1.PDMode) apiv1.PDDeploymentMode {
	switch mode {
	case v1alpha1.PDModeMS:
		return apiv1.PDDeploymentMode_PD_DEPLOYMENT_MODE_MICROSERVICE
	case v1alpha1.PDModeNormal:
		return apiv1.PDDeploymentMode_PD_DEPLOYMENT_MODE_MONOLITHIC
	default:
		return apiv1.PDDeploymentMode_PD_DEPLOYMENT_MODE_UNSPECIFIED
	}
}

func APIToPDMode(mode apiv1.PDDeploymentMode) v1alpha1.PDMode {
	if mode == apiv1.PDDeploymentMode_PD_DEPLOYMENT_MODE_MICROSERVICE {
		return v1alpha1.PDModeMS
	}
	return v1alpha1.PDModeNormal
}

func GetPDModeSwitchingCondition(pdGroup *v1alpha1.PDGroup) *metav1.Condition {
	for i := range pdGroup.Status.Conditions {
		if pdGroup.Status.Conditions[i].Type == v1alpha1.CondModeSwitching {
			return &pdGroup.Status.Conditions[i]
		}
	}
	return nil
}

func IsPDModeSwitchingTrue(condition *metav1.Condition) bool {
	return condition != nil && condition.Status == metav1.ConditionTrue
}

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

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

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

	return cvtPDComponentToEn(ctx, pdGroupCr)
}

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

	// get pd group
	var pdGroup v1alpha1.PDGroup
	key := types.NamespacedName{Name: groupId, Namespace: dataplaneNs}

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

	return &pdGroup, nil
}

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

	pdComponents := make([]*entity.Component, 0, len(pdGroups.Items))

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

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

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

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

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

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

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

	return compEn, nil
}

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

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

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

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

	return apiv1.Component_AVAILABLE
}

func getUpdateExpectedPDGroup(ctx context.Context, pdGroupCr *v1alpha1.PDGroup, 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 pd group %s", pdGroupCr.Name)
			}
			if count > 0 {
				currNodeQuota, err := CvtNodeSpecToQuota(pdGroupCr.Labels, pdGroupCr.Annotations, uint32(*pdGroupCr.Spec.Replicas), nil, nil)
				if err != nil {
					return false, status.Errorf(codes.Internal, "failed to convert node spec to quota for pd group %s: %s", pdGroupCr.Name, err)
				}

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

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

				if uint32(*pdGroupCr.Spec.Replicas) != count {
					pdGroupCr.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 pd group %s", pdGroupCr.Name)
			}

			resourceRequirements, err := setNodeSpec(nodeSpec, pdGroupCr.Labels, pdGroupCr.Spec.Template.Spec.Overlay.Pod.Spec.NodeSelector, apiv1.ComponentType_PD)
			if err != nil {
				tilog.Error(ctx, "set node spec", zap.Error(err))
				return false, fmt.Errorf("failed to set node spec for pd group %s: %w", pdGroupCr.Name, err)
			}
			for i := range pdGroupCr.Spec.Template.Spec.Overlay.Pod.Spec.Containers {
				if pdGroupCr.Spec.Template.Spec.Overlay.Pod.Spec.Containers[i].Name == "pd" {
					pdGroupCr.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 pd group %s", pdGroupCr.Name)
			}
			if maxCount > 0 {
				annotations := pdGroupCr.Annotations
				if annotations == nil {
					annotations = map[string]string{}
				}

				annotations[schemav1.AnnotationsComponentMaxCount] = fmt.Sprintf("%d", maxCount)
				pdGroupCr.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 := pdGroupCr.Annotations
			if annotations == nil {
				annotations = map[string]string{}
			}

			annotations[schemav1.AnnotationsComponentMinCount] = fmt.Sprintf("%d", minCount)
			pdGroupCr.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 pd group %s", pdGroupCr.Name)
			}
			if version != "" {
				pdGroupCr.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 pd group %s", pdGroupCr.Name)
			}
			if image != "" {
				pdGroupCr.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 pd group %s", pdGroupCr.Name)
			}
			if config != "" {
				pdGroupCr.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 pd group %s", pdGroupCr.Name)
			}
			if strategy != "" {
				pdGroupCr.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 pd group %s", pdGroupCr.Name)
			}
			nodeSelector := pdGroupCr.Spec.Template.Spec.Overlay.Pod.Spec.NodeSelector
			if nodeSelector == nil {
				nodeSelector = map[string]string{}
			}
			if nodeSelector[schemav1.K8sVersionLabelKey] != nodeVersion {
				nodeSelector[schemav1.K8sVersionLabelKey] = nodeVersion
				pdGroupCr.Spec.Template.Spec.Overlay.Pod.Spec.NodeSelector = nodeSelector
				needUpdate = true
			}
		}
	}

	for i := range pdGroupCr.Spec.Template.Spec.Volumes {
		// data
		if pdGroupCr.Spec.Template.Spec.Volumes[i].Name == string(schemav1.StorageData) {
			modigyVolume := false
			for _, opt := range options {
				switch opt.Option {
				case OpsUpdateDataSize:
					size, ok := opt.Value.(uint32)
					if !ok {
						tilog.Error(ctx, "invalid data storage size", zap.Any("value", opt.Value))
						return false, fmt.Errorf("invalid data storage size for pd group %s", pdGroupCr.Name)
					}
					sizeQuantity := resource.MustParse(fmt.Sprintf("%dGi", size))
					if size > 0 && pdGroupCr.Spec.Template.Spec.Volumes[i].Storage.Cmp(sizeQuantity) < 0 {
						pdGroupCr.Spec.Template.Spec.Volumes[i].Storage = sizeQuantity
						modigyVolume = true
						needUpdate = true
					}

				case OpsUpdateDataVolumeAttributesClass:
					volumeAttributesClass, ok := opt.Value.(string)
					if !ok {
						tilog.Error(ctx, "invalid data volume attributes class", zap.Any("value", opt.Value))
						return false, fmt.Errorf("invalid data volume attributes class for pd group %s", pdGroupCr.Name)
					}
					curr := lo.FromPtr(pdGroupCr.Spec.Template.Spec.Volumes[i].VolumeAttributesClassName)
					if volumeAttributesClass != "" && volumeAttributesClass != curr {
						pdGroupCr.Spec.Template.Spec.Volumes[i].VolumeAttributesClassName = lo.ToPtr(strings.ToLower(volumeAttributesClass))
						modigyVolume = true
						needUpdate = true
					}
				}
			}
			if modigyVolume {
				if pdGroupCr.Annotations == nil {
					pdGroupCr.Annotations = make(map[string]string)
				}
				pdGroupCr.Annotations[schemav1.AnnotationsUpdateTimeDataVolumeKey] = time.Now().Format(time.RFC3339)
			}
		}
	}

	return needUpdate, nil
}
