package premium

import (
	"strings"

	pb "github.com/tidbcloud/config-center/proto/config_center"
	"github.com/tidbcloud/config-center/templategen"
)

// IsV263 reports whether version is on the 26.3 line (tolerating an optional
// leading "v", so it matches both "26.3.2" and "v26.3.2").
func IsV263(version string) bool {
	return strings.HasPrefix(strings.TrimPrefix(version, "v"), "26.3")
}

// isPre263 reports whether version should use the pre-26.3 template deltas.
func isPre263(version string) bool {
	return !IsV263(version)
}

var specTiKV = templategen.Spec{
	ConfigType: pb.SHARED_POOL_CONFIG_TIKV,
	Name:       "system template of premium tikv",
	// Base holds the 26.3 config; Apply strips the 26.3-only keys for older lines.
	Base: templategen.MustTOML(`
[backup]
s3-multi-part-size = "30MB"

[cdc]
enable = true

[coprocessor]
enable-region-bucket = true
region-split-keys = 50000000
region-split-size = "500MiB"

[pd]
report-store-size-with-keyspace-name = true
load-all-keyspaces-on-start = true

[server]
simplify-metrics = true

[kvengine]
dfs-load-concurrency-per-core=32

[rfengine]
lightweight-backup = true
max-wal-chunk-gap-duration = "30m"
force-rotate-interval = "24h"
enable-compact-rate-limiter = true

[raftstore]
store-max-batch-size = 10240
main-worker-max-util = 60
aux-worker-max-util = 40

[security]
redact-info-log = true

[storage]
api-version = 2
check-backup-ts = true
enable-ttl = true

[readpool.unified]
use-tokio = false
`),
	Apply: func(version string, data map[string]*pb.ParamItem) {
		if !isPre263(version) {
			return
		}
		// 26.3-only keys: absent on the 8.5.x line.
		delete(data, "pd.report-store-size-with-keyspace-name")
		delete(data, "pd.load-all-keyspaces-on-start")
		delete(data, "rfengine.enable-compact-rate-limiter")
	},
}

// specTiKVWorker config is identical across 8.5.x and 26.3.
var specTiKVWorker = templategen.Spec{
	ConfigType: pb.SHARED_POOL_CONFIG_TIKV_WORKER,
	Name:       "system template of premium tikv worker",
	Base: templategen.MustTOML(`
[kvengine]
dfs-load-concurrency-per-core=32
`),
}

var specCoprocessorWorker = templategen.Spec{
	ConfigType: pb.SHARED_POOL_CONFIG_COPROCESSOR_WORKER,
	Name:       "system template of premium coprocessor worker",
	// Base holds the 26.3 config; Apply strips the 26.3-only [ia] keys for older lines.
	Base: templategen.MustTOML(`
[kvengine]
dfs-load-concurrency-per-core=32

[coprocessor-limiter]
global-concurrency-factor=8

[ia]
disk-cap = "80%"
mem-cap = "10%"
segment-size = 4194304
`),
	Apply: func(version string, data map[string]*pb.ParamItem) {
		if !isPre263(version) {
			return // 26.3+ uses Base as-is
		}
		delete(data, "ia.disk-cap")
		delete(data, "ia.mem-cap")
		delete(data, "ia.segment-size")
	},
}
