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 ListSchedulingGroups(ctx context.Context, remoteCli client.Client, clusterId string) ([]*entity.Component, error) {
	// Implementation for listing schedulings
	return listPDSchedulingGroups(ctx, remoteCli, dataplaneNamespace(clusterId))
}

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

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

	needUpdate, err := getUpdateExpectedSchedulingGroup(ctx, schedulingGroupCr, options...)
	if err != nil {
		return nil, fmt.Errorf("failed to get expected scheduling %s: %w", groupId, err)
	}

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

	return cvtPDSchedulingComponentToEn(ctx, schedulingGroupCr)
}

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

	// get pd scheduling group
	var pdSchedulingGroup v1alpha1.SchedulingGroup
	key := types.NamespacedName{Name: groupId, Namespace: dataplaneNs}

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

	return &pdSchedulingGroup, nil
}

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

	pdScheComponents := make([]*entity.Component, 0, len(ScheGroups.Items))

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

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

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

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

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

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

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

	return compEn, nil
}

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

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

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

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

	return apiv1.Component_AVAILABLE
}

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

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

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

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

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

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

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

	return needUpdate, nil
}
