package dedicatedapi

import (
	"fmt"
	"regexp"
	"strconv"
)

var stableKubernetesVersion = regexp.MustCompile(`^v(\d+)\.(\d+)\.(\d+)(?:\+k3s\d+)?$`)

// ControlPlaneImages are the upstream control-plane images matched to the
// host k3s patch version.
type ControlPlaneImages struct {
	KubernetesVersion      string
	APIServerImage         string
	ControllerManagerImage string
}

// ResolveControlPlaneImages strips only the k3s build suffix and rejects
// unknown minors or prereleases. CP9's executable compatibility window is
// intentionally explicit rather than following "latest".
func ResolveControlPlaneImages(gitVersion string) (*ControlPlaneImages, error) {
	match := stableKubernetesVersion.FindStringSubmatch(gitVersion)
	if match == nil {
		return nil, fmt.Errorf("unsupported host Kubernetes gitVersion %q: require a stable v1.x.y[+k3sN] release", gitVersion)
	}
	major, _ := strconv.Atoi(match[1])
	minor, _ := strconv.Atoi(match[2])
	if major != 1 || minor < 30 || minor > 35 {
		return nil, fmt.Errorf("unsupported host Kubernetes minor v%d.%d: tested Dedicated API minors are v1.30-v1.35", major, minor)
	}
	version := fmt.Sprintf("v%d.%d.%s", major, minor, match[3])
	return &ControlPlaneImages{
		KubernetesVersion:      version,
		APIServerImage:         "registry.k8s.io/kube-apiserver:" + version,
		ControllerManagerImage: "registry.k8s.io/kube-controller-manager:" + version,
	}, nil
}
