package consts

import (
	"fmt"

	cloudv1 "github.com/tidbcloud/infra-api/api/v1"
)

const (
	AnnotationKeyEKSEndpoint   = "infra.pingcap.com/eks-endpoint"
	AnnotationKeyEKSName       = "network.cloud.pingcap.com/eks-name"
	AnnotationKeyDataplaneName = "network.cloud.pingcap.com/dataplane"

	// GKE ILB Annotations //
	// AnnoKeyGKEOriginForwardingRuleName the origin FR key before enabling subsetting
	AnnoKeyGKEOriginForwardingRuleName = "cloud.pingcap.com/forwarding-rule"
	// AnnoKeyGKESubsettingILBHealthCheck the healthCheck path created by subsetting ILB
	AnnoKeyGKESubsettingILBHealthCheck = "service.kubernetes.io/healthcheck"
	// AnnoKeyGKESubsettingILBBackendService the backendService path created by subsetting ILB.
	// It is first referred in the GKE FullService task.
	AnnoKeyGKESubsettingILBBackendService = "service.kubernetes.io/backend-service"
	// AnnoKeyGKESubsettingILBForwardingRule the forwardingRule path created by subsetting ILB.
	// It is first referred in the GKE loadBalance task to check configuration of backendService.
	AnnoKeyGKESubsettingILBForwardingRule = "service.kubernetes.io/tcp-forwarding-rule"

	LastAppliedConfigAnnotation          = "tidbcloud.com/last-applied-configuration"
	NormalizeLastAppliedConfigAnnotation = "tidbcloud.com/normalize-last-applied-configuration"

	UseSelfManagedNodegroupAnnotation = "tidbcloud.com/use-self-managed-nodegroup"

	AuditLogSidecarAutoUpgrade = "tidbcloud.com/auditlog-sidecar-auto-upgrade"

	AuditLogSidecarImageTag = "tidbcloud.com/auditlog-sidecar-image-tag"

	// DestroyFinishedAtAnnotation records when every task in a child resource's
	// destroy pass completed without errors.
	DestroyFinishedAtAnnotation = "tidbcloud.com/destroy-finished-at"

	// AnnoKeyGKENodePoolComputeClass stores the desired GKE compute-class on a
	// shared NodePool CR so controllers and nodepool helpers can reconcile it consistently.
	AnnoKeyGKENodePoolComputeClass = "tidbcloud.com/gke-nodepool-compute-class"
	// AnnoKeyGKENodePoolComputeClassApplied records the compute-class label that
	// cluster-controller has observed from the GKE API. Readiness and delete guards
	// must use this instead of treating desired metadata as applied state.
	AnnoKeyGKENodePoolComputeClassApplied = "tidbcloud.com/gke-nodepool-compute-class-applied"
	// AnnoKeyGKEHeterogeneousNodePoolEverBound marks an API-managed extra GKE
	// nodepool that has ever been referenced by a heterogeneous compute-class intent.
	AnnoKeyGKEHeterogeneousNodePoolEverBound = "tidbcloud.com/gke-heterogeneous-nodepool-ever-bound"
	// AnnoKeyGKEHeterogeneousNodePoolScopeKey stores the human-readable ordinary
	// GKE nodepool naming scope behind GKEHeterogeneousNodePoolScopeLabelKey.
	AnnoKeyGKEHeterogeneousNodePoolScopeKey = "tidbcloud.com/gke-heterogeneous-nodepool-scope-key"

	AnnoKeyNodePoolLastUsedTime = "tidbcloud.com/nodepool-gc-last-used-time"
	AnnoKeyNodePoolGCExpiredAt  = "tidbcloud.com/nodepool-gc-expired-at"
	AnnoKeyNodePoolGCApprovedAt = "tidbcloud.com/nodepool-gc-approved-at"
	AnnoKeyNodePoolGCLastScanAt = "tidbcloud.com/nodepool-gc-last-scan-at"

	// ClusterFeatureUseSelfSignedCertForTiDBComponents indicates using self-signed certificates for inter-components mTLS communication
	ClusterFeatureUseSelfSignedCertForTiDBComponents = "self-signed-cert-for-tidb-components"

	// ClusterFeatureSelfSignedCertForTidbServer indicates using self-signed certificate for tidb server on SQL port
	// This feature should be used for development test only
	ClusterFeatureSelfSignedCertForTidbServer = "self-signed-cert-for-tidb-server"

	// ClusterFeatureShortLivedComponentCert makes the PCA-issued cluster
	// certificates short-lived (see consts.ShortLivedComponentCertDuration) while
	// keeping the AWS Private CA issuer. It exists for environments whose PCA runs
	// in SHORT_LIVED_CERTIFICATE mode, which cannot sign the default long-lived
	// (10-year) certificate. Unlike the self-signed features it does not change
	// the issuer, so the CA a MySQL client verifies against is unchanged.
	ClusterFeatureShortLivedComponentCert = "short-lived-component-cert"

	// ClusterFeatureUseAtRestEncryption is formal version of cluster-controller/controllers/cluster/task/common/tidbcluster.go:annoKeyEnableKMS
	ClusterFeatureUseAtRestEncryption = "at-rest-encryption" // see also https://docs.pingcap.com/tidb/stable/encryption-at-rest
	// ClusterFeatureNoScaleOutTiDBInParallel is used to disable to scale out tidb in parallel
	ClusterFeatureNoScaleOutTiDBInParallel = "no-scale-out-tidb-in-parallel"
	ClusterFeatureUseCMEK                  = cloudv1.ClusterFeatureUseCMEK
	// ClusterFeatureDedicatedSG is used to decide whether to use dedicated security group for managing traffic filter(white-list)
	// for public LB. For AWS only.
	ClusterFeatureDedicatedSG            = "dedicated-sg"
	ClusterFeatureTiDBExposeOOMPath      = "tidb-expose-oom-path"
	ClusterFeatureTiDBExposeReplayerPath = "tidb-expose-replayer-path"

	// ClusterFeatureWildcardDNS indicates whether to use wildcard DNS for tidb-server
	ClusterFeatureWildcardDNS = "wildcard-dns"

	// ClusterFeatureDisableNodePoolDataPlaneLabel disable cluster-controller to set GKE nodepool's NodeConfig.Labels with
	// cloud.pingcap.com/node-group-type: "data-plane" because change it will cause existing nodes without this label restart.
	ClusterFeatureDisableNodePoolDataPlaneLabel = "disable-nodepool-data-plane-label"

	// ClusterFeatureGCP3LayerNodePool add taint and label to new nodepool in 3-layer
	// It's designed to avoid pods of migrated clusters being scheduled to 3-layer nodepool, which may break customers' authorization config of audit log
	// NOTE: it's only worked for gcp but will enabled for all clouds(for later deprecating process)
	// NOTE: As history reason, the feature name is "3-layer-node-pool" but actually it's only for gcp.
	//       And it's been applied to all newly created clusters including AWS, GCP and Azure.
	ClusterFeatureGCP3LayerNodePool = "3-layer-node-pool"

	// Deprecated: use ClusterFeatureTiProxyCertLayoutLegacy instead.
	// ClusterFeatureTiProxyCertLayoutV1 is used for switch certificate layout from legacy to v1, which is required by
	// self-signed certificate feature.
	// Enable this feature for clusters without tiproxy has no impacts.
	ClusterFeatureTiProxyCertLayoutV1 = "tiproxy-cert-layout-v1"

	// ClusterFeatureTiProxyCertLayoutLegacy is used for compatibility with the existing clusters which have tiproxy running with
	// legacy cert layout.
	ClusterFeatureTiProxyCertLayoutLegacy = "tiproxy-cert-layout-legacy"

	// ClusterFeatureSetPriorityClass is used to set priority class for all pods in the tidb cluster.
	// Since it needs to restart pods for existing clusters, let's only enable it for newly created clusters.
	ClusterFeatureSetPriorityClass = "set-priority-class"

	// ClusterFeatureUseTiDBOperatorV2 is used to enable TiDB Operator v2 to manage tidb clusters.
	ClusterFeatureUseTiDBOperatorV2 = "use-tidb-operator-v2"

	// ClusterFeatureDisableClusterAutoscaler is used to disable cluster-autoscaler to manage tidb clusters (e.g. ASG tags for self-managed nodegroup).
	ClusterFeatureDisableClusterAutoscaler = "disable-cluster-autoscaler"

	// ClusterFeatureScaleStatusTrack is used to enable scale status track for tidb clusters.
	ClusterFeatureScaleStatusTrack = "scale-status-track"

	// ClusterFeatureNodeScalingCheck is used to enable node-level scaling check for TiDB components.
	ClusterFeatureNodeScalingCheck = "scale-check-node"

	// ClusterFeatureUseVolumeAttributesClass is used to enable VAC to modify volumes in tidb operator v2.
	ClusterFeatureUseVolumeAttributesClass = "use-volume-attributes-class"

	// ClusterFeatureDisableScheduleTiProxyInTheSameZoneWithTiDB is used to disable scheduling tiproxy in the same zone with tidb.
	ClusterFeatureDisableScheduleTiProxyInTheSameZoneWithTiDB = "disable-schedule-tiproxy-in-the-same-zone-with-tidb"

	// ClusterFeatureDisableSyncTiDBSpecChangesForEnablingTiproxy is used to disable syncing TiDB spec changes to TiDB when TiProxy is enabled.
	ClusterFeatureDisableSyncTiDBSpecChangesForEnablingTiproxy = "disable-sync-tidb-spec-changes-for-enabling-tiproxy"

	// ClusterFeatureLegacyTiProxySettings is used for compatibility with the existing clusters.
	// For clusters with this feature enabled, the tiproxy will use the legacy settings:
	// 1. configure `graceful-wait-before-shutdown` to 15 seconds for tidb instead of 30 seconds
	// 2. create tiproxy pods WITHOUT readiness probe
	// 3. use dynamic calculated value for `terminationGracePeriodSeconds` of tiproxy pods instead of constant 20 minutes.
	ClusterFeatureLegacyTiProxySettings = "legacy-tiproxy-settings"

	// ClusterFeatureDisableV2PDReadinessProbe is used to disable readiness probe of pd in tidb operator v2
	ClusterFeatureDisableV2PDReadinessProbe = "disable-v2-pd-readiness-probe"

	// ClusterFeatureEnableGracefulShutdown is used to enable graceful shutdown for tidb clusters.
	// When it's enabled, will do a serials of optimizations to make sure the cluster can be gracefully shutdown.
	ClusterFeatureEnableGracefulShutdown = "enable-graceful-shutdown"

	// ClusterFeatureRemoveNEGAnnotation is used to remove the annotation "cloud.google.com/neg" for k8s services.
	ClusterFeatureRemoveNEGAnnotation = "remove-neg-annotation"

	// ClusterFeatureUsePDReadyAPIV2 is used to enable the PD ready API with tidb operator v2.
	ClusterFeatureUsePDReadyAPIV2 = "use-pd-ready-api-v2"

	// ClusterFeatureUsePPv2TiDBComponents is used to enable PPv2 launch-configs for TiDB.
	ClusterFeatureUsePPv2TiDBComponents = "ppv2-tidb-components"

	// ClusterFeatureUsePPv2TiProxy is used to enable PPv2 launch-configs for TiProxy.
	ClusterFeatureUsePPv2TiProxy = "ppv2-tiproxy-components"

	// ClusterFeatureUsePPv2PrivateNLB is used to enable PPv2 attributes for private-NLB (25/09/09 AWS only).
	ClusterFeatureUsePPv2PrivateNLB = "ppv2-private-nlb"

	// ClusterFeatureEnableTiFlashGracefulShutdown is used to enable graceful shutdown for tiflash instance.
	ClusterFeatureEnableTiFlashGracefulShutdown = "enable-tiflash-graceful-shutdown"

	// ClusterFeatureEnableTiFlashGracefulShutdownSleep controls whether to enable the sleep behavior during TiFlash graceful shutdown.
	ClusterFeatureEnableTiFlashGracefulShutdownSleep = "enable-tiflash-graceful-shutdown-sleep"

	// EOL
	// ClusterFeatureScaleWithWorkflow indicates whether to use workflow to scale the cluster.
	// ClusterFeatureScaleWithWorkflow = "scale-with-workflow"

	// AnnoKeyOverrideTiFlashGracefulShutdownSleepSeconds defines the wait time for TiFlash to flush logs to stdout before shutdown.
	AnnoKeyOverrideTiFlashGracefulShutdownSleepSeconds = "override.tidbcloud.com/tiflash-graceful-shutdown-sleep-seconds"

	AnnoValTrue = "true"

	ClusterUpdateAnnotationKeyInstanceType = cloudv1.AnnoClusterUpdateAnnotationKeyInstanceType

	// Deprecated: use ClusterFeatureUseCMEK instead.
	// CMEKEnabled indicates whether the cluster is using CMEK.
	CMEKEnabledKey = "eks.infra.pingcap.com/cmek-enabled"

	// KMSEnabledKey is the annotation key for whether the cluster enables kernel at reset encryption
	KMSEnabledKey = "tikv.cloud.pingcap.com/enable-kms"

	// This annotation is used for setting control plane's version.
	// New cluster will be created after EKS/GKE ClusterStatus.NodeVersion is set now.
	// But the NodeVersion can not be set for some existing clusters because it has been used
	// for some names and selectors.
	// It's only for compatibility now.
	AnnoKeyControlPlaneVersion = "cluster.cloud.pingcap.com/control-plane-version"

	// TcInstanceTypeAnnotationKey indicates the current instance type used in TidbCluster.
	TcInstanceTypeAnnotationKey = "infra.pingcap.com/instance-type"

	AnnoInstanceTypeSeparator = cloudv1.AnnoInstanceTypeSeparator

	AnnSysctlInit    = "tidb.pingcap.com/sysctl-init"
	AnnSysctlInitVal = "true"

	DefaultLoadBalancerIDAnnotationKey = "tidbcloud.com/default-tidbgroup-access-id"

	O11yAgentReleaseNamespace       = "o11y.cloud.pingcap.com/release-namespace"
	O11yServiceDNSNameAnnotationKey = "o11y.cloud.pingcap.com/service-dns-name"
	O11yClusterStatusAnnotationKey  = "o11y.cloud.pingcap.com/status"
	// O11yIDAnnotationKey is added to a Network CR, represents s3/gcs id in o11y infra.
	O11yIDAnnotationKey = "o11y.cloud.pingcap.com/id"
	// MetricInterfaceEndpointNameAnnotationKey is added to a Cluster CR.
	MetricInterfaceEndpointNameAnnotationKey = "o11y.cloud.pingcap.com/metric-interface-endpoint-name"
	S3GatewayEndpointNameAnnotationKey       = "o11y.cloud.pingcap.com/s3-gateway-endpoint-name"
	// MetricsO11yIDAnnotationKey represents prometheus id in o11y infra.
	MetricsO11yIDAnnotationKey = "o11y.cloud.pingcap.com/metrics-id"

	// AnnoKeyTiProxyToggleWorkflow records the currently running tiproxy toggle workflow.
	// This annotation will be automatically deleted once this workflow is finished.
	// If a cluster is annotated with this annotation, the cluster-server will return `clusterPhase: SYNCING`
	// even if `cluster.FullSynced() == true`.
	AnnoKeyTiProxyToggleWorkflow = "tidbcloud.com/tiproxy-toggle-workflow"
	// AnnoKeyWaitTimeForToggleLBTarget represents the wait time for toggle lb target.
	// The default value is 300s.
	AnnoKeyWaitTimeForToggleLBTarget = "tidbcloud.com/wait-time-for-toggle-lb-target"
	// AnnoKeyLBTargetOnTiProxyPrefix indicates whether the LB target is on TiProxy.
	// the group id will be appended to form the annotation key.
	AnnoKeyLBTargetOnTiProxyPrefix = "flag.tidbcloud.com/lb-target-on-tiproxy"

	// AnnoKeyScaleOutTiProxyWorkflow records the currently running scaling workflow.
	// If a cluster is annotated with this annotation, the cluster-server will return `clusterPhase: SYNCING`
	// even if `cluster.FullSynced() == true`.
	AnnoKeyScaleClusterWorkflow = "tidbcloud.com/scale-cluster-workflow"

	// AnnoClusterResourceStatusDiff records whether the cluster resource status is different from the desired status.
	AnnoClusterResourceStatusDiff = "tidbcloud.com/cluster-resource-status-diff"

	// AnnoCancelWorkflow records whether the workflow is cancelled.
	AnnoCancelWorkflow = "tidbcloud.com/cancel-workflow"

	// AnnoKeyAZFaultActive marks the cluster as under AZ fault handling
	// (e.g. AWS ARC zonal shift). Value is the fault AZ name (e.g. "us-east-1a").
	// Set by START_ZONAL_SHIFT; cleared by STOP_ZONAL_SHIFT after cleanup.
	AnnoKeyAZFaultActive = "tidbcloud.com/az-fault-active"

	AnnoKeyOverrideAuditLogSidecarGracefulStopWaitSeconds = "override.tidbcloud.com/auditlog-sidecar-graceful-stop-wait-seconds"
)

const (
	// AnnoValueBugNameTokenBasedAuthNotEnabled indicates this cluster has a bug that the field Tc.Spec.TiDB.TokenBasedAuthEnabled
	// was set to True, but this cluster actually did not support token-based-auth. see https://pingcap-cn.feishu.cn/wiki/BoOkwHiCciPF6yk54QUcLed0nnf.
	AnnoValueBugNameTokenBasedAuthNotEnabled = "token-based-auth-not-enabled"

	// AnnoValueBugNameCMEKNotEnabled indicates this cluster want to enable CMEK but actually not,
	// refer to https://pingcap.feishu.cn/wiki/VyYswDSTgiTe3rkBkAdcNtlWnte
	AnnoValueBugNameCMEKNotEnabled = "cmek-not-enabled"
)

func AnnoKeyLBTargetOnTiProxy(groupID string) string {
	return fmt.Sprintf("%s-%s", AnnoKeyLBTargetOnTiProxyPrefix, groupID)
}
