package router

import (
	"context"

	"github.com/pingcap/tiproxy/pkg/manager/router"
	"github.com/pkg/errors"
	"github.com/tidbcloud/aws-shared-provider/pkg/infra"
	"github.com/tidbcloud/aws-shared-provider/pkg/utils/kubeapi"
	corev1 "k8s.io/api/core/v1"
	ctrl "sigs.k8s.io/controller-runtime"
)

type healthChecker struct {
	router    *Router
	token     string
	clusterID string
	localKube infra.LocalKube
}

func (h *healthChecker) Check(ctx context.Context, addr string, info *router.BackendInfo) *router.BackendHealth {
	logger := ctrl.Log.WithName("backendHealthCheck").WithValues("token", h.token).
		WithValues("cluster_id", h.clusterID).WithValues("backendIP", info.IP)

	podList, err := h.localKube.GetPodList(ctx, info.IP)
	if err != nil {
		logger.Error(err, "failed to list pods")
		return &router.BackendHealth{Status: router.StatusHealthy} // still return healthy
	}
	var backendTidbPod *corev1.Pod
	if len(podList.Items) > 0 {
		backendTidbPod = &podList.Items[0]
	}
	if backendTidbPod == nil {
		logger.Info("pod is not found")
		if len(h.router.GetBackendIPs()) <= 1 {
			// no need to check backend health if there is only one backend
			return &router.BackendHealth{Status: router.StatusHealthy}
		}
		return &router.BackendHealth{Status: router.StatusCannotConnect, PingErr: errors.New("pod not found")}
	}
	if !kubeapi.IsPodReady(backendTidbPod) {
		logger.Info("pod is not ready", "pod", backendTidbPod.Namespace+"/"+backendTidbPod.Name)
		if len(h.router.GetBackendIPs()) <= 1 {
			// no need to check backend health if there is only one backend
			return &router.BackendHealth{Status: router.StatusHealthy}
		}
		return &router.BackendHealth{Status: router.StatusCannotConnect, PingErr: errors.New("pod not ready")}
	}
	// if backendTidbPod.Annotations[types.AnnoTidbStatusRunSlow] != "" {
	// 	logger.Info("pod is RunSlow", "pod", backendTidbPod.Namespace+"/"+backendTidbPod.Name)
	// 	return &router.BackendHealth{Status: router.StatusRunSlow}
	// }

	return &router.BackendHealth{Status: router.StatusHealthy}
}
