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

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

	return cvtPDTsoComponentToEn(ctx, tsoGroupCr)
}

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

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

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

	return cvtPDTsoComponentToEn(ctx, tsoGroupCr)
}

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

	// get pd tso group
	var pdTsoGroup v1alpha1.TSOGroup
	key := types.NamespacedName{Name: groupId, Namespace: dataplaneNs}

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

	return &pdTsoGroup, nil
}

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

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

	for i := range pdTsoGroups.Items {
		compEn, err := cvtPDTsoComponentToEn(ctx, &pdTsoGroups.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 cvtPDTsoComponentToEn(ctx context.Context, tsoGroups *v1alpha1.TSOGroup) (*entity.Component, error) {
	compEn := &entity.Component{
		Id:            strings.Split(tsoGroups.Name, "-")[1], // db-<Id>-tidb
		ComponentType: apiv1.ComponentType_PD_TSO,
	}
	setTemplateVersionFromAnnotations(compEn, tsoGroups.Annotations)

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

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

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

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

	return compEn, nil
}

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

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

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

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

	return apiv1.Component_AVAILABLE
}

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

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

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

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

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

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

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

	return needUpdate, nil
}
