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

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

	return cvtTiProxyComponentToEn(ctx, tiproxyGroupCr)
}

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

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

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

	return cvtTiProxyComponentToEn(ctx, tiproxyGroupCr)
}

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

	// get tiproxy group
	var tiproxyGroup v1alpha1.TiProxyGroup
	key := types.NamespacedName{Name: groupId, Namespace: dataplaneNs}

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

	return &tiproxyGroup, nil
}

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

	tiproxyComponents := make([]*entity.Component, 0, len(tiproxyGroups.Items))

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

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

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

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

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

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

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

	return compEn, nil
}

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

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

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

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

	return apiv1.Component_AVAILABLE
}

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

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

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

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

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

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

			annotations[schemav1.AnnotationsComponentMinCount] = fmt.Sprintf("%d", minCount)
			tiproxyGroupCr.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 tiproxy group %s", tiproxyGroupCr.Name)
			}
			if version != "" {
				tiproxyGroupCr.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 tiproxy group %s", tiproxyGroupCr.Name)
			}
			if image != "" {
				tiproxyGroupCr.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 tiproxy group %s", tiproxyGroupCr.Name)
			}
			if config != "" {
				tiproxyGroupCr.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 tiproxy group %s", tiproxyGroupCr.Name)
			}
			if strategy != "" {
				tiproxyGroupCr.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 tiproxy group %s", tiproxyGroupCr.Name)
			}
			if labels != nil {
				serverLabels := tiproxyGroupCr.Spec.Template.Spec.Server.Labels
				if serverLabels == nil {
					serverLabels = map[string]string{}
				}
				// merge labels
				for k, v := range labels {
					serverLabels[k] = v
				}
				tiproxyGroupCr.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 tiproxy group %s", tiproxyGroupCr.Name)
			}
			nodeSelector := tiproxyGroupCr.Spec.Template.Spec.Overlay.Pod.Spec.NodeSelector
			if nodeSelector == nil {
				nodeSelector = map[string]string{}
			}
			if nodeSelector[schemav1.K8sVersionLabelKey] != nodeVersion {
				nodeSelector[schemav1.K8sVersionLabelKey] = nodeVersion
				tiproxyGroupCr.Spec.Template.Spec.Overlay.Pod.Spec.NodeSelector = nodeSelector
				needUpdate = true
			}
		}
	}

	return needUpdate, nil
}
