package config

import (
	"time"

	apprent "github.com/tidbcloud/devops/entity/approval"
)

type Services struct {
	InternalToken      InternalTokenServiceConfig   `yaml:"internalToken"`
	Approval           ApprovalServiceConfig        `yaml:"approval"`
	Release            ReleaseSerivceConfig         `yaml:"release"`
	Application        ApplicationServiceConfig     `yaml:"application"`
	ClusterCtl         ClusterCtlServiceConfig      `yaml:"clusterCtl"`
	ClusterMaintenance ClusterMaintenanceConfig     `yaml:"clusterMaintenance"`
	Monitoring         MonitoringServiceConfig      `yaml:"monitoring"`
	Incident           IncidentServiceConfig        `yaml:"incident"`
	Tenant             TenantServiceConfig          `yaml:"tenant"`
	Dashboard          DashboardServiceConfig       `yaml:"dashboard"`
	Github             GithubServiceConfig          `yaml:"github"`
	Operation          OperationServiceConfig       `yaml:"operation"`
	Jump               JumpServiceConfig            `yaml:"jump"`
	Alert              AlertServiceConfig           `yaml:"alert"`
	CloudConfig        CloudConfigServiceConfig     `yaml:"cloudConfig"`
	PremiumUpgrade     PremiumUpgradeServiceConfig  `yaml:"premiumUpgrade"`
	UserBehavior       UserBehaviorServiceConfig    `yaml:"userbehavior"`
	K8sUpgrade         K8sUpgradeServiceConfig      `yaml:"k8sUpgrade"`
	K8sCalendar        K8sCalendarServiceConfig     `yaml:"k8sCalendar"`
	RemediationTicket  RemediationTicketConfig      `yaml:"remediationTicket"`
	Privilege          PrivilegeServiceConfig       `yaml:"privilege"`
	AutoCredit         AutoCreditServiceConfig      `yaml:"autoCredit"`
	ActiveEMEATenant   ActiveEMEATenantReportConfig `yaml:"activeEMEATenant"`
	KernelImage        KernelImageServiceConfig     `yaml:"kernelImage"`
	FeatureGates       FeatureGatesConfig           `yaml:"featureGates"`
}

type KernelImageServiceConfig struct {
	Enabled                bool                               `yaml:"enabled" default:"false"`
	LocalDevOpsEnvironment string                             `yaml:"localDevOpsEnvironment"`
	SelectionPolicy        KernelImageSelectionPolicy         `yaml:"selectionPolicy"`
	FID                    KernelImageFIDConfig               `yaml:"fid"`
	BYOCSync               KernelImageBYOCSyncConfig          `yaml:"byocSync"`
	AvailabilityCheck      KernelImageAvailabilityCheckConfig `yaml:"availabilityCheck"`
}

type KernelImageSelectionPolicy struct {
	VersionCount  int `yaml:"versionCount" default:"2"`
	ImageTagCount int `yaml:"imageTagCount" default:"4"`
}

type KernelImageFIDConfig struct {
	RepositoryOwner   string `yaml:"repositoryOwner"`
	RepositoryName    string `yaml:"repositoryName"`
	QueueLabelPrefix  string `yaml:"queueLabelPrefix" default:"delivery-queue-tidbx"`
	QueueCommentLimit int    `yaml:"queueCommentLimit" default:"2000"`
}

type KernelImageBYOCSyncConfig struct {
	Enabled  bool           `yaml:"enabled" default:"false"`
	Ref      string         `yaml:"ref" default:"main"`
	Workflow string         `yaml:"workflow"`
	MaxWait  *time.Duration `yaml:"maxWait" default:"2h"`
}

type KernelImageAvailabilityCheckConfig struct {
	CronDisable bool   `yaml:"cronDisable" default:"false"`
	CronSpec    string `yaml:"cronSpec" default:"0 0 * * *"`
	Concurrency int    `yaml:"concurrency" default:"2"`
}

type FeatureGatesConfig struct {
	K8sUpgradeClusterMaintenance ScopedFeatureGate `yaml:"k8supgradeClusterMaintenance"`
}

type ScopedFeatureGate struct {
	All      bool     `yaml:"all"`
	Tenants  []string `yaml:"tenants"`
	Projects []string `yaml:"projects"`
}

func (g *ScopedFeatureGate) Enabled(tenantID, projectID string) bool {
	if g.All {
		return true
	}
	for _, t := range g.Tenants {
		if t == tenantID {
			return true
		}
	}
	for _, p := range g.Projects {
		if p == projectID {
			return true
		}
	}
	return false
}

type InternalTokenServiceConfig struct {
	DefaultTTL    *time.Duration `yaml:"defaultTTL" default:"15m"`
	KeyID         string         `yaml:"keyID" validate:"required"`         // READ FROM ASM
	SigningKeyPEM string         `yaml:"signingKeyPEM" validate:"required"` // READ FROM ASM
}

type ReleaseSerivceConfig struct {
	SyncReleaseFromJiraInitDelay *time.Duration `yaml:"syncReleaseFromJiraInitDelay" default:"5m"`
	WatchTicketsFromJiraInterval *time.Duration `yaml:"watchTicketsFromJiraInterval" default:"12h"`
	WarchTicketsUpdatedDaysAgo   int            `yaml:"warchTicketsUpdatedDaysAgo" default:"7"`

	Project string `yaml:"project" default:"DM" validate:"required"`

	// WatchChangeInterval is the interval to watch uncompleted changes.
	WatchChangeInterval *time.Duration `yaml:"watchChangeInterval" default:"5m"`
	// NotifyChatID is the lark chat ID to notify change events.
	NotifyChatID string `yaml:"notifyChatID" validate:"required"`
	// LastApproverEmails are fixed approvers.
	LastApproverEmails []string `yaml:"lastApproverEmails"` // user email
	// Approvers for Ng Image Build
	NgImageBuildApproverEmailsMap map[string][]string `yaml:"ngImageBuildApproverEmailsMap"` // repo -> user email list
	// MinDeployInterval is the minimum waiting time between two deployments.
	MinDeployInterval *time.Duration `yaml:"minDeployInterval" default:"6h"`
	// MinObserveDuration is the minimum duration to observe a change.
	MinObserveDuration *time.Duration `yaml:"minObserveDuration" default:"10m"`
	// NotifyToCloseInterval is the interval to notify the applicant to close a change.
	NotifyToCloseInterval *time.Duration `yaml:"notifyToCloseInterval" default:"24h"`
}

type ApprovalServiceConfig struct {
	TemplatesFilepath           string `yaml:"templatesFilepath" validate:"required"`
	FixedAdminApproverUserGroup string `yaml:"fixedAdminApproverUserGroup"`
	DisableAdminApprove         bool   `yaml:"disableAdminApprove"`
}

type ApplicationServiceConfig struct {
}

type ClusterCtlServiceConfig struct {
	ExecutorServerAddr string   `yaml:"executorServerAddr"`
	AuthServerAddr     string   `yaml:"authServerAddr"`
	BlockedCommands    []string `yaml:"blockedCommands"`
}

type ClusterMaintenanceConfig struct {
	Dummy bool `yaml:"dummy"`

	// NotifyChatID is the lark chat ID to notify maintenance events.
	NotifyChatID                  string         `yaml:"notifyChatID" validate:"required_if=Dummy false"`
	MaintenanceEmailCheckInternal *time.Duration `yaml:"maintenanceEmailCheckInterval" default:"60s"`
	EmailFromAddress              string         `yaml:"emailFromAddress" validate:"required_if=Dummy false"`
	BeforeTemplateID              string         `yaml:"beforeTemplateID" validate:"required_if=Dummy false"`
	StartedTemplateID             string         `yaml:"startedTemplateID" validate:"required_if=Dummy false"`
	CompletedTemplateID           string         `yaml:"completedTemplateID" validate:"required_if=Dummy false"`
	FirstInterval                 string         `yaml:"firstInterval" default:"3 day"`
	NextInterval                  string         `yaml:"nextInterval" default:"14 day"`
}

type DbaasAddrConfig struct {
	CoreServiceAddr       string            `yaml:"coreServiceAddr" validate:"required"`
	OpsCoreServiceAddr    string            `yaml:"opsCoreServiceAddr" validate:"required"`
	MgmtServiceAddr       string            `yaml:"mgmtServiceAddr" validate:"required"`
	NextGenGlobalAddr     string            `yaml:"nextGenGlobalAddr" validate:"required" default:"nextgen-global-service.tidb-management-service.svc:10000"`
	AccountServiceAddr    string            `yaml:"accountServiceAddr" validate:"required"`
	AccountHttpAddr       string            `yaml:"accountHttpAddr"`
	BillingServiceAddr    string            `yaml:"billingServiceAddr" validate:"required"`
	ServerlessServiceAddr string            `yaml:"serverlessServiceAddr" validate:"required"`
	ConfigCenterAddr      string            `yaml:"configCenterAddr" validate:"required" default:"config-center:8080"`
	DataflowServiceAddr   string            `yaml:"dataflowServiceAddr" validate:"required"`
	DataflowNgServiceAddr string            `yaml:"dataflowNgServiceAddr" validate:"required"`
	MgmtPortalServiceAddr string            `yaml:"mgmtPortalServiceAddr" validate:"required"`
	O11yServiceAddr       string            `yaml:"o11yServiceAddr" validate:"required"`
	CloudInfraMetaDB      DatabaseConfig    `yaml:"cloudInfraMetaDB" validate:"required"`
	MgmtService           MgmtServiceConfig `yaml:"mgmtService" validate:"required"`
}

type AutoCreditServiceConfig struct {
	CronDisable     bool           `yaml:"cronDisable" default:"false"`
	CronSpec        string         `yaml:"cronSpec" validate:"required_if=CronDisable false"`
	SheetID         string         `yaml:"sheetID"`
	SheetRange      string         `yaml:"sheetRange"`
	CreditAmount    string         `yaml:"creditAmount" validate:"required_if=CronDisable false"`
	Usage           string         `yaml:"usage" validate:"required_if=CronDisable false"`
	Provider        string         `yaml:"provider"`
	DiscountEnabled bool           `yaml:"discountEnabled" default:"true"`
	NotePrefix      string         `yaml:"notePrefix" validate:"required_if=CronDisable false"`
	ExpiredAfter    *time.Duration `yaml:"expiredAfter" default:"720h"`
	DryRun          bool           `yaml:"dryRun" default:"false"`
	OperatorEmail   string         `yaml:"operatorEmail" default:"fan.wang@pingcap.com" validate:"required_if=CronDisable false"`
	BindTypeIDs     []uint64       `yaml:"bindTypeIDs"`
}

type ActiveEMEATenantReportConfig struct {
	CronDisable             bool           `yaml:"cronDisable" default:"false"`
	CronSpec                string         `yaml:"cronSpec" default:"0 9 * * *" validate:"required_if=CronDisable false"`
	DryRun                  bool           `yaml:"dryRun" default:"false"`
	OperatorEmail           string         `yaml:"operatorEmail" default:"fan.wang@pingcap.com" validate:"required_if=CronDisable false"`
	PageSize                int            `yaml:"pageSize" default:"500"`
	AccountCountryAllowList []string       `yaml:"accountCountryAllowList"`
	MinActiveClusterCount   *int           `yaml:"minActiveClusterCount"`
	CandidateProfileTTL     *time.Duration `yaml:"candidateProfileTTL" default:"24h"`
	EnrichmentTTL           *time.Duration `yaml:"enrichmentTTL" default:"720h"`
	EnrichmentSchemaVersion string         `yaml:"enrichmentSchemaVersion" default:"v1"`
	ReportS3Prefix          string         `yaml:"reportS3Prefix" default:"active-emea-tenant-report"`
	LarkFolderToken         string         `yaml:"larkFolderToken"`
	LarkAppCode             string         `yaml:"larkAppCode"`
	LarkAppSecret           string         `yaml:"larkAppSecret"`
	NotifyChatID            string         `yaml:"notifyChatID" validate:"required_if=CronDisable false"`
	OpsPortalBaseURL        string         `yaml:"opsPortalBaseURL" default:"https://ops.tidbcloud.com"`
}

type CertMonitoringServiceConfig struct {
	CronDisable  bool     `yaml:"cronDisable" default:"false"`
	CronSpec     string   `yaml:"cronSpec"`
	ClinicToken  string   `yaml:"clinicToken"`
	GrantType    string   `yaml:"grantType"`
	ClientID     string   `yaml:"clientID"`
	ClientSecret string   `yaml:"clientSecret"`
	Audience     string   `yaml:"audience"`
	BizType      string   `yaml:"bizType"`
	Env          string   `yaml:"env"`
	Regions      []string `yaml:"regions"`
}

type CompDiffReportMonitoringServiceConfig struct {
	CronDisable          bool   `yaml:"cronDisable" default:"false"`
	CronSpec             string `yaml:"cronSpec"`
	CleanCronSpec        string `yaml:"cleanCronSpec"`
	ReportRetentionCount int    `yaml:"reportRetentionCount" default:"10"`
}

type IdleReminderServiceConfig struct {
	WeeklyReport WeeklyReportConfig `yaml:"weekly_report"`
	JiraReport   JiraReportConfig   `yaml:"jira_report"`
}

type WeeklyReportConfig struct {
	CronDisable      bool     `yaml:"cronDisable" default:"false"`
	CronSpec         string   `yaml:"cronSpec"`
	TemplateID       string   `yaml:"template_id"`
	EmailFromAddress string   `yaml:"email_from_address"`
	ReceiverEmails   []string `yaml:"receiver_emails"`
	CC               []string `yaml:"cc"`
	BCC              []string `yaml:"bcc"`
}

type JiraReportConfig struct {
	JiraSpec []JiraSpecConfig `yaml:"jiraSpec"`
	// CronDisable      bool             `yaml:"cronDisable" default:"false"`
	// CronSpec         string           `yaml:"cronSpec"`
	// TemplateID       string           `yaml:"template_id"`
	// EmailFromAddress string           `yaml:"email_from_address" validate:"required"`
	// ReceiverEmails   []string         `yaml:"receiver_emails"`
	// CC               []string         `yaml:"cc"`
	// BCC              []string         `yaml:"bcc"`
}

type JiraSpecConfig struct {
	CronDisable          bool     `yaml:"cronDisable" default:"false"`
	CronSpec             string   `yaml:"cronSpec"`
	JQL                  string   `yaml:"jql"`
	MailEnable           bool     `yaml:"mailEnable"`
	TemplateID           string   `yaml:"template_id"`
	EmailFromAddress     string   `yaml:"email_from_address" validate:"required"`
	ReceiverEmails       []string `yaml:"receiver_emails"`
	CC                   []string `yaml:"cc"`
	BCC                  []string `yaml:"bcc"`
	NotifyTarget         string   `yaml:"notify_target" default:"both"`
	NotifyTargetWithMail bool     `yaml:"notify_target_with_mail" default:"false"`
}

type MonitoringServiceConfig struct {
	Dummy bool `yaml:"dummy"`

	Certificate              CertMonitoringServiceConfig           `yaml:"certificate"`
	ComponentDiffReport      CompDiffReportMonitoringServiceConfig `yaml:"compoent_diff_report"`
	IdleReminder             IdleReminderServiceConfig             `yaml:"idle_reminder"`
	ClusterAnomalyDetections []ClusterAnomalyDetectionConfig       `yaml:"cluster_anomaly_detections"`
}

type ClusterAnomalyDetectionConfig struct {
	CronDisable      bool     `yaml:"cron_disable" default:"false"`
	CronSpec         string   `yaml:"cron_spec"`
	TemplateID       string   `yaml:"template_id"`
	EmailFromAddress string   `yaml:"email_from_address"`
	ReceiverEmails   []string `yaml:"receiver_emails"`
	CC               []string `yaml:"cc"`
	BCC              []string `yaml:"bcc"`

	ClusterIDs        []string           `yaml:"cluster_ids"`
	LongUnfinishedSQL *LongUnfinishedSQL `yaml:"top_sql_detection"`
}

type LongUnfinishedSQL struct {
	Enabled  bool   `yaml:"enabled" default:"true"`
	Duration string `yaml:"duration" default:"1h"`
}

type IncidentServiceConfig struct {
	Dummy bool `yaml:"dummy"`

	ReportChatId                         string                    `yaml:"reportChatId"`
	OpsPortalBaseURL                     string                    `yaml:"opsPortalBaseURL"`
	OverdueToDoActionReminderCronDisable bool                      `yaml:"overdueToDoActionReminderCronDisable" default:"false"`
	OverdueToDoActionReminderCronSpec    string                    `yaml:"overdueToDoActionReminderCronSpec" default:"0 9 * * *"`
	ComponentOptions                     []string                  `yaml:"componentOptions"`
	ComponentDefinitions                 []IncidentComponentConfig `yaml:"components"`
}

type IncidentComponentConfig struct {
	Key           string `yaml:"key"`
	Name          string `yaml:"name"`
	Enabled       *bool  `yaml:"enabled"`
	Order         int    `yaml:"order"`
	T1RuleSummary string `yaml:"t1RuleSummary"`
	T2RuleSummary string `yaml:"t2RuleSummary"`
	T3RuleSummary string `yaml:"t3RuleSummary"`
	RuleDocURL    string `yaml:"ruleDocURL"`
}

type TenantServiceConfig struct {
	CronDisable        bool     `yaml:"cronDisable" default:"false"`
	CronSpec           string   `yaml:"cronSpec" validate:"required_if=CronDisable false"`
	TenantTableName    string   `yaml:"tenantTableName"`
	O11yEndpoint       string   `yaml:"o11yEndpoint"`
	PrometheusPath     string   `yaml:"prometheusPath"`
	TestInfraTenantIDs []uint64 `yaml:"testInfraTenantIDs"`
}

type DashboardServiceConfig struct {
	Dummy bool `yaml:"dummy"`

	SlaDB                        *DatabaseConfig `yaml:"slaDB" validate:"required_if=Dummy false"`
	ServerlessSlaDB              *DatabaseConfig `yaml:"serverlessSlaDB" validate:"required_if=Dummy false"`
	EEPrometheusEndpoint         string          `yaml:"eePrometheusEndpoint" validate:"required_if=Dummy false"`
	BasePrometheusEndpoint       string          `yaml:"basePrometheusEndpoint" validate:"required_if=Dummy false"`
	SyncSLAInterval              *time.Duration  `yaml:"syncSLAInterval" default:"15m"`
	SyncSLOInterval              *time.Duration  `yaml:"syncSLOInterval" default:"15m"`
	SyncDedicatedClusterInterval *time.Duration  `yaml:"syncDedicatedClusterInterval" default:"10m"`
}

type GithubServiceConfig struct {
	Dummy bool `yaml:"dummy"`

	DisableSync                bool           `yaml:"disableSync" default:"false"`
	SyncRepositoryInterval     *time.Duration `yaml:"syncRepositoryInterval" default:"12h"`
	SyncRepositoryPushedBefore *time.Duration `yaml:"syncRepositoryPushedBefore" default:"720h"` // default 30 days
	BuiltinRepositories        []string       `yaml:"builtinRepositories"`
	SyncPullRequestInterval    *time.Duration `yaml:"syncPullRequestInterval" default:"30m"`
}

type OperationServiceConfig struct {
	// SyncInstanceInterval is the interval to sync instances.
	SyncInstanceInterval *time.Duration `yaml:"syncInstanceInterval" default:"30s"`
	// OperationRegistryFilepath is the filepath to the operation registry.
	OperationRegistryFilepath string `yaml:"operationRegistryFilepath" validate:"required"`
	// OperationNotifiyWehookURL
	OperationNotifiyWehookURL string `yaml:"operationNotifyWehookURL"`
	// OperationClusterWhiteList is used to control that restart dm operation can only be performed on specified clusters.
	OperationClusterWhiteList map[string]ClusterDMInfo `yaml:"operationClusterWhiteList"`
}

type JumpServiceConfig struct {
	WatchJumpAuthorizationInterval       *time.Duration `yaml:"watchJumpAuthorizationInterval" default:"30s"`
	WatchJumpAuthorizationSlowlyInterval *time.Duration `yaml:"watchJumpAuthorizationSlowlyInterval" default:"10m"`
	SyncJumpPodInterval                  *time.Duration `yaml:"syncJumpPodInterval" default:"1h"`
	ForceFinilizeJumpThreshold           *time.Duration `yaml:"forceFinilizeJumpThreshold" default:"12h"`
	JumpPodRecycleThresold               *time.Duration `yaml:"jumpPodRecycleThreshold" default:"1h"`
	DestinationRegistryFilepath          string         `yaml:"destinationRegistryFilepath" validate:"required"`
	JumpRoleDir                          string         `yaml:"jumpRoleDir" default:"./jump_roles"`
	GrantSEEPrivilegeCron                string         `yaml:"grantSEEPrivilegeCron" default:""`
	SyncOncallerInterval                 *time.Duration `yaml:"syncOncallerInterval" default:"30m"`

	Console   JumpServiceJumpServerConsoleConfig `yaml:"console"`
	Gateway   JumpServiceGatewayConfig           `yaml:"gateway"`
	Dedicated JumpServiceDedicatedConfig         `yaml:"dedicated"`
	Premium   JumpServicePremiumConfig           `yaml:"premium"`
	JumpPod   JumpServiceJumpPodConfig           `yaml:"jumpPod"`
	Tailscale JumpServiceTailscaleClientConfig   `yaml:"tailscale"`
}

type JumpServiceGatewayConfig struct {
	AccessURL string `yaml:"accessURL"`
	Audience  string `yaml:"audience"`
}

type JumpServiceJumpServerConsoleConfig struct {
	JumpServerAddr            string `yaml:"jumpServerAddr"`
	JumpServerSSHAddr         string `yaml:"jumpServerSSHAddr"`
	JumpServerAccessUrl       string `yaml:"jumpServerAccessUrl"`
	JumpServerAccessKeyID     string `yaml:"jumpServerAccessKeyID" validate:"required"`     // READ FROM ASM
	JumpServerAccessKeySecret string `yaml:"jumpServerAccessKeySecret" validate:"required"` // READ FROM ASM
	JumpServerBaseAssetName   string `yaml:"jumpServerBaseAssetName"`
}

type JumpServiceDedicatedConfig struct {
	DedicatedNewArchAccessRole string                           `yaml:"dedicatedNewArchAccessRole"` // Empty means pod role is used
	DedicatedAKSAuth           *JumpServiceDestinationAzureAuth `yaml:"dedicatedAKSAuth"`
}

type JumpServicePremiumConfig struct {
	PremiumACKAuth *JumpServiceDestinationAliCloudAuth `yaml:"premiumACKAuth"`
	PremiumAKSAuth *JumpServiceDestinationAzureAuth    `yaml:"premiumAKSAuth"`
}

type JumpServiceJumpPodConfig struct {
	Provider             string `yaml:"provider" default:"eks"` // eks, ack
	JumpPodNamespace     string `yaml:"jumpPodNamespace" default:"jump-service"`
	JumpPodImage         string `yaml:"jumpPodImage" validate:"required"`
	JumpPodAgentImage    string `yaml:"jumpPodAgentImage" validate:"required"`
	JumpPodRoleARN       string `yaml:"jumpPodRoleARN" validate:"required"`
	JumpPodCPULimit      string `yaml:"jumpPodCPULimit" default:"100m"`
	JumpPodMemLimit      string `yaml:"jumpPodMemLimit" default:"100Mi"`
	JumpPodAgentCPULimit string `yaml:"jumpPodAgentCPULimit" default:"100m"`
	JumpPodAgentMemLimit string `yaml:"jumpPodAgentMemLimit" default:"100Mi"`
	JumpPodSharedFSAddr  string `yaml:"jumpPodSharedFSAddr" validate:"required"`
}

type JumpServiceTailscaleClientConfig struct {
	TailscaleClientID     string   `yaml:"tailscaleClientID" validate:"required"`     // READ FROM ASM
	TailscaleClientSecret string   `yaml:"tailscaleClientSecret" validate:"required"` // READ FROM ASM
	TailscaleAuthKeyTags  []string `yaml:"tailscaleAuthKeyTags"`
	TailscaleTailnetName  string   `yaml:"tailscaleTailnetName" default:"pingcap.com"`
}

type JumpServiceDestinationAWSAuth struct {
	Region     string `yaml:"region"`
	AssumeRole string `yaml:"assumeRole"`
	ExternalID string `yaml:"externalID"`
}

type JumpServiceDestinationGCPAuth struct {
}

type JumpServiceDestinationAzureAuth struct {
	// SubscriptionID is the subscription ID of the Azure subscription.
	SubscriptionID string `yaml:"subscriptionID" validate:"required"`
	// TenantID is the tenant ID of the Azure subscription.
	TenantID string `yaml:"tenantID" validate:"required"`
	// ClientID is the client ID of the Azure Managed Identity.
	//
	// NOTE: the Managed Identity MUST be federated with the federated token in pod.
	ClientID string `yaml:"clientID" validate:"required"`
	// FederatedTokenFilepath is the path of the federated token which used to exchange Managed Identity token.
	FederatedTokenFilepath string `yaml:"federatedTokenFilepath" validate:"required"`
}

type JumpServiceDestinationCertAuth struct {
	FromSecret *JumpServiceDestinationCertAuthFromSecret `yaml:"fromSecret"`
}

type JumpServiceDestinationCertAuthFromSecret struct {
	SecretName string `yaml:"secretName"`
}

type JumpServiceDestinationAliCloudAuth struct {
	ClusterID   string `yaml:"clusterID"`
	ProfileName string `yaml:"profileName"`
	ProfileFile string `yaml:"profileFile"`
}

type JumpServiceDestination struct {
	Type string `yaml:"type"`
	Name string `yaml:"name"`

	K8sName     string `yaml:"k8sName"`
	K8sEndpoint string `yaml:"k8sEndpoint"`

	AWSAuth      *JumpServiceDestinationAWSAuth      `yaml:"awsAuth"`
	GCPAuth      *JumpServiceDestinationGCPAuth      `yaml:"gcpAuth"`
	AzureAuth    *JumpServiceDestinationAzureAuth    `yaml:"azureAuth"`
	AliCloudAuth *JumpServiceDestinationAliCloudAuth `yaml:"alicloudAuth"`
	CertAuth     *JumpServiceDestinationCertAuth     `yaml:"certAuth"`
}

type AlertServiceConfig struct {
	Dummy bool `yaml:"dummy"`

	JiraProject string `yaml:"jiraProject" default:"O11Y" validate:"required_if=Dummy false"`
}

type CloudConfigServiceConfig struct {
	Dummy bool `yaml:"dummy"`

	SyncClusterConfigChangeInterval        *time.Duration    `yaml:"syncClusterConfigChangeInterval" default:"30s"`
	SyncDefaultConfigChangeReleaseInterval *time.Duration    `yaml:"syncDefaultConfigChangeReleaseInterval" default:"10m"`
	SubEnvironments                        []string          `yaml:"subEnvironments"`
	SubEnvironmentAPIKeys                  map[string]string `yaml:"subEnvironmentAPIKeys"` // READ FROM ASM
}

type PremiumUpgradeServiceConfig struct {
	Dummy *bool `yaml:"dummy"`

	ScanInterval          *time.Duration               `yaml:"scanInterval" default:"30s"`
	ConflictRetryInterval *time.Duration               `yaml:"conflictRetryInterval" default:"1m"`
	ApplyDeadline         *time.Duration               `yaml:"applyDeadline" default:"6h"`
	MaxParallelTargets    uint32                       `yaml:"maxParallelTargets" default:"3"`
	DetailLinkBaseURL     string                       `yaml:"detailLinkBaseURL"`
	Approval              PremiumUpgradeApprovalConfig `yaml:"approval"`
}

type PremiumUpgradeApprovalConfig struct {
	Nodes            []PremiumUpgradeApprovalNodeConfig           `yaml:"nodes"`
	DefaultGroup     string                                       `yaml:"defaultGroup"`
	Groups           map[string]PremiumUpgradeApproverGroupConfig `yaml:"groups"`
	RepositoryGroups map[string]string                            `yaml:"repositoryGroups"`
	ComponentGroups  map[string]string                            `yaml:"componentGroups"`
}

type PremiumUpgradeApprovalNodeConfig struct {
	apprent.Approver `yaml:",inline"`

	Name          string                `yaml:"name"`
	Method        apprent.ApproveMethod `yaml:"method"`
	SkipWhenEmpty bool                  `yaml:"skipWhenEmpty"`
	Condition     string                `yaml:"condition"`
	Components    []string              `yaml:"components"`
	Repositories  []string              `yaml:"repositories"`
	Default       bool                  `yaml:"default"`
}

type PremiumUpgradeApproverGroupConfig struct {
	Emails     []string `yaml:"emails"`
	UserGroups []string `yaml:"userGroups"`
}

type UserBehaviorServiceConfig struct {
	Dummy bool `yaml:"dummy"`

	SyncLarkChatsInterval  *time.Duration           `yaml:"syncLarkChatsInterval" default:"10m"`
	ScanDMJobEventInterval *time.Duration           `yaml:"scanDMJobEventInterval" default:"10m"`
	GTM                    GTMConfig                `yaml:"gtm"`
	TenantEventCapture     TenantEventCaptureConfig `yaml:"tenantEventCapture"`
}

type TenantEventCaptureConfig struct {
	Enabled     bool            `yaml:"enabled" default:"false"`
	AutoMigrate bool            `yaml:"autoMigrate" default:"false"`
	TargetDB    *DatabaseConfig `yaml:"targetDB"`

	Regions           []string `yaml:"regions"`
	ExcludedPlans     []string `yaml:"excludedPlans"`
	ExcludedTenantIDs []uint64 `yaml:"excludedTenantIDs"`
	Countries         []string `yaml:"countries"`

	EventFilters map[string]TenantEventCaptureEventFilter `yaml:"eventFilters"`
}

type TenantEventCaptureEventFilter struct {
	EventTypes       []string `yaml:"eventTypes"`
	ExcludedStatuses []string `yaml:"excludedStatuses"`
}

// GTMConfig configures GTM (Go-To-Market) automation for lead qualification and outreach
type GTMConfig struct {
	Enabled             bool     `yaml:"enabled" default:"false"`
	EnabledGeoSelectors []string `yaml:"enabledGeoSelectors"`
	// EmailDisabledGeoSelectors qualifies and persists matching leads, but does not compose or queue email.
	EmailDisabledGeoSelectors []string `yaml:"emailDisabledGeoSelectors"`
	MockToAddress             string   `yaml:"mockToAddress"`

	FromName               string           `yaml:"fromName" default:"TiDB Cloud Sales"`
	FromAddress            string           `yaml:"fromAddress" default:"sales@tidbcloud.com"`
	EmailDelay             time.Duration    `yaml:"emailDelay" default:"6h"`
	EmailQueueScanInterval time.Duration    `yaml:"emailQueueScanInterval" default:"5m"`
	InternalCCList         []string         `yaml:"internalCCList"`
	UseCaseProfiles        []UseCaseProfile `yaml:"useCaseProfiles"`
	NotifyUserIDs          []string         `yaml:"notifyUserIDs"` // Lark user IDs to @ in GTM result cards
}

// UseCaseProfile defines a GTM target use case with matching criteria and messaging
type UseCaseProfile struct {
	Name                   string   `yaml:"name"`
	Description            string   `yaml:"description"`
	CustomerReferences     []string `yaml:"customerReferences"`
	RequiredKeywords       []string `yaml:"requiredKeywords"`
	PreferredBusinessModel string   `yaml:"preferredBusinessModel"`
}

type K8sCalendarProviderConfig struct {
	URL string `yaml:"url"`
}

type K8sCalendarServiceConfig struct {
	Dummy        bool           `yaml:"dummy"`
	SyncInterval *time.Duration `yaml:"syncInterval"`
	EOSLeadDays  int            `yaml:"eosLeadDays"`
	// MinNotifyVersion skips all calendar notifications for versions strictly below this value (e.g. "1.28").
	MinNotifyVersion string                    `yaml:"minNotifyVersion" default:"1.33"`
	UserAgent        string                    `yaml:"userAgent"`
	EKS              K8sCalendarProviderConfig `yaml:"eks"`
	GKE              K8sCalendarProviderConfig `yaml:"gke"`
}

type K8sUpgradePlanServiceConfig struct {
	Dummy                 bool           `yaml:"dummy"`
	ScanInterval          *time.Duration `yaml:"scanInterval"`
	DefaultDeadlineBuffer *time.Duration `yaml:"defaultDeadlineBuffer"`
	DefaultUpgraderBuffer *time.Duration `yaml:"defaultUpgraderBuffer"`
	AdminApprovers        []string       `yaml:"adminApprovers"`
	AdminEmailTemplateID  string         `yaml:"adminEmailTemplateID"`
}

type K8sUpgradeNoticeTemplateConfig struct {
	Title   string `yaml:"title"`
	Content string `yaml:"content"`
}

type K8sUpgradeNotifyConfig struct {
	// PageURLBase is the base URL for the k8s upgrade task page.
	PageURLBase string `yaml:"pageURLBase"`

	// NoticeTemplate is the config for the k8s upgrade notice template.
	NoticeTemplate K8sUpgradeNoticeTemplateConfig `yaml:"noticeTemplate"`

	// Channels is the list of notification channels to use.
	Channels []string `yaml:"channels" default:"[\"lark_group\"]"`

	// channel: LarkGroup
	// LarkWebhookMap maps business region -> lark webhook URL.
	LarkWebhookMap map[string]string `yaml:"larkWebhookMap"`
	// DefaultWebhook is the fallback webhook URL.
	DefaultWebhook string `yaml:"defaultWebhook"`
	// LarkCardTemplateID is the message card template id for webhook notifications.
	LarkCardTemplateID string `yaml:"larkCardTemplateID"`

	// channel: Email
	// EmailTemplateID is the sendgrid template id for email notifications.
	EmailTemplateID string `yaml:"emailTemplateID"`
	// RegionEmailMap maps business region -> fixed notification email recipients.
	// When set for a region, sales owner / TAM emails on matching targets are ignored.
	RegionEmailMap map[string][]string `yaml:"regionEmailMap"`
}

type K8sUpgradeServiceConfig struct {
	Dummy bool `yaml:"dummy"`

	SyncUpgradeTasksInterval  *time.Duration    `yaml:"syncUpgradeTasksInterval"`
	DetailLinkBaseURL         string            `yaml:"detailLinkBaseURL" validate:"required_if=Dummy false"`
	K8sUpgradeTaskApprovers   []string          `yaml:"k8sUpgradeTaskApprovers"`
	K8sUpgradeTaskCCUserGroup map[string]string `yaml:"k8sUpgradeTaskCCUserGroup"`
	K8sUpgradeTaskCCEmails    []string          `yaml:"k8sUpgradeTaskCCEmails"`
	// LarkWebhook is the webhook to send k8s upgrade notifications.
	LarkWebhook string `yaml:"larkWebhook"`
	// SupportedEOSVersions is the list of supported target k8s versions, keyed by cloud provider (e.g. aws/gcp).
	SupportedEOSVersions map[string][]string `yaml:"supportedEOSVersions"`
	// GeneratorConfig is the config for generating UpgradeOperation steps.
	GeneratorConfig   K8sUpgradeGeneratorConfig   `yaml:"generatorConfig"`
	Notify            K8sUpgradeNotifyConfig      `yaml:"notify"`
	UpgradePlanConfig K8sUpgradePlanServiceConfig `yaml:"upgradePlanConfig"`
}

type K8sUpgradeGeneratorConfig struct {
	// EKSAddonsConfig stores the version of EKS addons.
	// The key is the version of EKS, and the value is the version of the addons.
	EKSAddonsConfig map[string][]EKSAddon `yaml:"eksAddonsConfig"`
}

type RemediationTicketConfig struct {
	Dummy bool `yaml:"dummy"`

	ResponsiblePersons              RTResponsiblePersonConfig `yaml:"responsiblePersons"`
	WatchRemediationTicketsInterval *time.Duration            `yaml:"watchRemediationTicketsInterval" default:"60s"`
	Workflow                        RemediationWorkflowConfig `yaml:"workflow"`
	SuccessApprovalCCByBizRegion    map[string][]string       `yaml:"successApprovalCCByBizRegion"`
}

type RemediationWorkflowConfig struct {
	Default RemediationWorkflowDefinitionConfig `yaml:"default"`
}

type RemediationWorkflowDefinitionConfig struct {
	Phases         []string          `yaml:"phases"`
	Labels         map[string]string `yaml:"labels"`
	OptionalPhases []string          `yaml:"optionalPhases"`
}

type PrivilegeServiceConfig struct {
	Dummy bool `yaml:"dummy"`

	DisableCron                   bool           `yaml:"disableCron" default:"false"`
	WatchPrivilegesInterval       *time.Duration `yaml:"watchPrivilegesInterval" default:"3m"`
	WatchPrivilegesSlowlyInterval *time.Duration `yaml:"watchPrivilegesSlowlyInterval" default:"30m"`
}

type RTResponsiblePersonConfig struct {
	RegionTSELeader       RTRegionTSELeaderConfig       `yaml:"regionTSELeader"`
	RDGSLAOwner           RTRDGSLAOwnerConfig           `yaml:"rdgSLAOwner"`
	RDGFinalDecisionMaker RTRDGFinalDecisionMakerConfig `yaml:"rdgFinalDecisionMaker"`
	GlobalDealDesk        RTGlobalDealDeskConfig        `yaml:"globalDealDesk"`
	RegionalGM            RTRegionalGMConfig            `yaml:"regionalGM"`
	CommercialOperation   RTCommercialOperationConfig   `yaml:"commercialOperation"`
}

type RTRegionTSELeaderConfig struct {
	APAC   string `yaml:"APAC" default:"xieyujie@pingcap.com"`
	EMEA   string `yaml:"EMEA" default:"xieyujie@pingcap.com"`
	JP     string `yaml:"JP" default:"xieyujie@pingcap.com"`
	NA     string `yaml:"NA" default:"xieyujie@pingcap.com"`
	Backup string `yaml:"Backup" default:"xieyujie@pingcap.com"`
}

type RTRDGSLAOwnerConfig struct {
	ServerlessPerson string `yaml:"serverlessPerson" default:"xieyujie@pingcap.com"`
	DediacatedPerson string `yaml:"dedicatedPerson" default:"xieyujie@pingcap.com"`
}

type RTRDGFinalDecisionMakerConfig struct {
	Person string `yaml:"person" default:"xieyujie@pingcap.com"`
}

type RTGlobalDealDeskConfig struct {
	Person string `yaml:"person" default:"xieyujie@pingcap.com"`
}

type RTRegionalGMConfig struct {
	APAC   string `yaml:"APAC" default:"xieyujie@pingcap.com"`
	EMEA   string `yaml:"EMEA" default:"xieyujie@pingcap.com"`
	JP     string `yaml:"JP" default:"xieyujie@pingcap.com"`
	NA     string `yaml:"NA" default:"xieyujie@pingcap.com"`
	Backup string `yaml:"Backup" default:"xieyujie@pingcap.com"`
}

type RTCommercialOperationConfig struct {
	Person string `yaml:"person" default:"xieyujie@pingcap.com"`
}

type EKSAddon struct {
	Name    string `yaml:"name"`
	Version string `yaml:"version"`
}

type ClusterDMInfo struct {
	TenantID        string `yaml:"tenantID" validate:"required"`
	ClusterAgentURL string `yaml:"clusterAgentURL" validate:"required"`
}
