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 ListTiKVGroups(ctx context.Context, remoteCli client.Client, clusterId string) ([]*entity.Component, error) {
	return listTiKVGroups(ctx, remoteCli, dataplaneNamespace(clusterId))
}

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

	return cvtTiKVComponentToEn(ctx, tikvGroupCr)
}

func GetTiKVGroupRemoteWorkerNames(ctx context.Context, remoteCli client.Client, clusterID, groupID string) (TiKVRemoteWorkerTarget, error) {
	group, err := getTiKVGroupCR(ctx, remoteCli, dataplaneNamespace(clusterID), groupID)
	if err != nil {
		if apierrors.IsNotFound(err) {
			return TiKVRemoteWorkerTarget{}, status.Errorf(codes.NotFound, "tikv group %s not found: %s", groupID, err)
		}
		return TiKVRemoteWorkerTarget{}, status.Errorf(codes.Internal, "failed to get tikv group %s: %s", groupID, err)
	}
	return tiKVRemoteWorkerTargetFromGroup(group), nil
}

func TiKVGroupRemoteWorkersReady(group *v1alpha1.TiKVGroup, expected TiKVRemoteWorkerTarget) bool {
	if group == nil || expected.Worker == "" || expected.Coprocessor == "" ||
		tiKVRemoteWorkerTargetFromGroup(group) != expected {
		return false
	}
	groupStatus := group.Status
	if groupStatus.ObservedGeneration != group.Generation || groupStatus.CurrentRevision == "" ||
		groupStatus.UpdateRevision == "" || groupStatus.CurrentRevision != groupStatus.UpdateRevision ||
		group.Spec.Replicas == nil || groupStatus.Replicas != *group.Spec.Replicas ||
		groupStatus.ReadyReplicas != groupStatus.Replicas || groupStatus.UpdatedReplicas != groupStatus.Replicas ||
		groupStatus.CurrentReplicas != groupStatus.Replicas {
		return false
	}
	return tiKVGroupConditionAtGeneration(groupStatus.Conditions, v1alpha1.CondReady, group.Generation) &&
		tiKVGroupConditionAtGeneration(groupStatus.Conditions, v1alpha1.CondSynced, group.Generation)
}

func tiKVRemoteWorkerTargetFromGroup(group *v1alpha1.TiKVGroup) TiKVRemoteWorkerTarget {
	if group == nil || group.Spec.Template.Spec.RemoteWorkers == nil {
		return TiKVRemoteWorkerTarget{}
	}
	remoteWorkers := group.Spec.Template.Spec.RemoteWorkers
	target := TiKVRemoteWorkerTarget{Worker: remoteWorkers.Worker.Name}
	if remoteWorkers.Coprocessor != nil {
		target.Coprocessor = remoteWorkers.Coprocessor.Name
	}
	return target
}

func tiKVGroupConditionAtGeneration(conditions []metav1.Condition, conditionType string, generation int64) bool {
	for _, condition := range conditions {
		if condition.Type == conditionType && condition.Status == metav1.ConditionTrue && condition.ObservedGeneration == generation {
			return true
		}
	}
	return false
}

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

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

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

	return cvtTiKVComponentToEn(ctx, tikvGroupCr)
}

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

	// get tikv group
	var tikvGroup v1alpha1.TiKVGroup
	key := types.NamespacedName{Name: groupId, Namespace: dataplaneNs}

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

	return &tikvGroup, nil
}

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

	tikvComponents := make([]*entity.Component, 0, len(tikvGroups.Items))

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

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

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

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

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

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

	compEn.Storages, err = cvtStoragesToEn(ctx, tikvGroup.Spec.Template.Spec.Volumes)
	if err != nil {
		return nil, err
	}
	compEn.Phase = getTiKVGroupStatus(ctx, tikvGroup)
	// set labels from server labels
	if tikvGroup.Spec.Template.Spec.Server.Labels != nil {
		compEn.Labels = tikvGroup.Spec.Template.Spec.Server.Labels
	}

	return compEn, nil
}

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

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

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

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

	return apiv1.Component_AVAILABLE
}

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

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

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

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

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

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

			annotations[schemav1.AnnotationsComponentMinCount] = fmt.Sprintf("%d", minCount)
			tikvGroupCr.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 tikv group %s", tikvGroupCr.Name)
			}
			if version != "" {
				tikvGroupCr.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 tikv group %s", tikvGroupCr.Name)
			}
			if image != "" {
				tikvGroupCr.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 tikv group %s", tikvGroupCr.Name)
			}
			if config != "" {
				tikvGroupCr.Spec.Template.Spec.Config = v1alpha1.ConfigFile(config)
				needUpdate = true

				// tikv worker managed by tioperator will auto set the tikv spec when tikv config changed
				// if not will lost tikv worker config after tikv config updated
				// TODO: remove this loop after tioperator support tikv worker config management
				if tikvGroupCr.Spec.Template.Spec.RemoteWorkers == nil {
					tikvGroupCr.Spec.Template.Spec.RemoteWorkers = &v1alpha1.TiKVRemoteWorkers{
						Worker: v1alpha1.WorkerReference{
							Name: fmt.Sprintf("%s-default", tikvGroupCr.Name),
						},
						Coprocessor: &v1alpha1.CoprocessorReference{
							Name: fmt.Sprintf("%s-coprocessor", tikvGroupCr.Name),
						},
					}
				}
			}
		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 tikv group %s", tikvGroupCr.Name)
			}
			if strategy != "" {
				tikvGroupCr.Spec.Template.Spec.UpdateStrategy.Config = strategy
				needUpdate = true
			}
		case OpsUpdateLabels:
			labels, ok := opt.Value.(map[string]string)
			if !ok {
				tilog.Error(ctx, "invalid labels", zap.Any("value", opt.Value))
				return false, fmt.Errorf("invalid labels for tikv group %s", tikvGroupCr.Name)
			}
			if labels != nil {
				serverLabels := tikvGroupCr.Spec.Template.Spec.Server.Labels
				if serverLabels == nil {
					serverLabels = map[string]string{}
				}
				// merge labels
				for k, v := range labels {
					serverLabels[k] = v
				}
				tikvGroupCr.Spec.Template.Spec.Server.Labels = serverLabels
				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 tikv group %s", tikvGroupCr.Name)
			}
			nodeSelector := tikvGroupCr.Spec.Template.Spec.Overlay.Pod.Spec.NodeSelector
			if nodeSelector == nil {
				nodeSelector = map[string]string{}
			}
			if nodeSelector[schemav1.K8sVersionLabelKey] != nodeVersion {
				nodeSelector[schemav1.K8sVersionLabelKey] = nodeVersion
				tikvGroupCr.Spec.Template.Spec.Overlay.Pod.Spec.NodeSelector = nodeSelector
				needUpdate = true
			}
		case OpsUpdateTiKVRemoteWorkers:
			target, ok := opt.Value.(TiKVRemoteWorkerTarget)
			if !ok || target.Worker == "" || target.Coprocessor == "" {
				return false, fmt.Errorf("invalid TiKV remote worker target for tikv group %s", tikvGroupCr.Name)
			}
			remoteWorkers := tikvGroupCr.Spec.Template.Spec.RemoteWorkers
			if remoteWorkers == nil {
				remoteWorkers = &v1alpha1.TiKVRemoteWorkers{}
				tikvGroupCr.Spec.Template.Spec.RemoteWorkers = remoteWorkers
			}
			if remoteWorkers.Worker.Name != target.Worker {
				remoteWorkers.Worker.Name = target.Worker
				needUpdate = true
			}
			if remoteWorkers.Coprocessor == nil {
				remoteWorkers.Coprocessor = &v1alpha1.CoprocessorReference{}
			}
			if remoteWorkers.Coprocessor.Name != target.Coprocessor {
				remoteWorkers.Coprocessor.Name = target.Coprocessor
				needUpdate = true
			}
		}
	}

	for i := range tikvGroupCr.Spec.Template.Spec.Volumes {
		// data
		if tikvGroupCr.Spec.Template.Spec.Volumes[i].Name == string(schemav1.StorageData) {
			modifyVolume := 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 tikv group %s", tikvGroupCr.Name)
					}

					sizeQuantity := resource.MustParse(fmt.Sprintf("%dGi", size))
					if size > 0 && tikvGroupCr.Spec.Template.Spec.Volumes[i].Storage.Cmp(sizeQuantity) < 0 {
						tikvGroupCr.Spec.Template.Spec.Volumes[i].Storage = sizeQuantity
						modifyVolume = 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 tikv group %s", tikvGroupCr.Name)
					}
					curr := lo.FromPtr(tikvGroupCr.Spec.Template.Spec.Volumes[i].VolumeAttributesClassName)
					if volumeAttributesClass != "" && volumeAttributesClass != curr {
						tikvGroupCr.Spec.Template.Spec.Volumes[i].VolumeAttributesClassName = lo.ToPtr(strings.ToLower(volumeAttributesClass))
						modifyVolume = true
						needUpdate = true
					}
				}
			}
			if modifyVolume {
				if tikvGroupCr.Annotations == nil {
					tikvGroupCr.Annotations = make(map[string]string)
				}
				tikvGroupCr.Annotations[schemav1.AnnotationsUpdateTimeDataVolumeKey] = time.Now().Format(time.RFC3339)
			}
		}

		// raftlog
		if tikvGroupCr.Spec.Template.Spec.Volumes[i].Name == string(schemav1.StorageRaftLog) {
			modifyVolume := false
			for _, opt := range options {
				switch opt.Option {
				case OpsUpdateRaftLogSize:
					size, ok := opt.Value.(uint32)
					if !ok {
						tilog.Error(ctx, "invalid raft log storage size", zap.Any("value", opt.Value))
						return false, fmt.Errorf("invalid raft log storage size for tikv group %s", tikvGroupCr.Name)
					}
					sizeQuantity := resource.MustParse(fmt.Sprintf("%dGi", size))
					if size > 0 && tikvGroupCr.Spec.Template.Spec.Volumes[i].Storage.Cmp(sizeQuantity) < 0 {
						tikvGroupCr.Spec.Template.Spec.Volumes[i].Storage = sizeQuantity
						modifyVolume = true
						needUpdate = true
					}
				case OpsUpdateRaftLogVolumeAttributesClass:
					volumeAttributesClass, ok := opt.Value.(string)
					if !ok {
						tilog.Error(ctx, "invalid raft log volume attributes class", zap.Any("value", opt.Value))
						return false, fmt.Errorf("invalid raft log volume attributes class for tikv group %s", tikvGroupCr.Name)
					}
					curr := lo.FromPtr(tikvGroupCr.Spec.Template.Spec.Volumes[i].VolumeAttributesClassName)
					if volumeAttributesClass != "" && volumeAttributesClass != curr {
						tikvGroupCr.Spec.Template.Spec.Volumes[i].VolumeAttributesClassName = lo.ToPtr(strings.ToLower(volumeAttributesClass))
						modifyVolume = true
						needUpdate = true
					}
				}
			}
			if modifyVolume {
				if tikvGroupCr.Annotations == nil {
					tikvGroupCr.Annotations = make(map[string]string)
				}
				tikvGroupCr.Annotations[schemav1.AnnotationsUpdateTimeRaftLogVolumeKey] = time.Now().Format(time.RFC3339)
			}
		}
	}

	return needUpdate, nil
}
