/*
Copyright 2022 The Kubernetes Authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package applyset

import (
	"encoding/json"
	"strings"

	"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
	"k8s.io/apimachinery/pkg/runtime/schema"
	"k8s.io/apimachinery/pkg/util/sets"
	"k8s.io/klog/v2"
)

// readyConditionTypes lists the status condition types whose "True" status means the object
// is healthy, and whose "False" status means it is not.
//
// Conditions of any other type are ignored, because a "False" status there carries no
// information about the object's health. Controllers routinely publish conditions that are
// purely informational (KEDA sets "Paused" to "False" on every ScaledObject it is actively
// scaling) or that report an abnormal state as "True" (a healthy Node reports "MemoryPressure"
// as "False"). Treating those as failures marks such objects permanently unhealthy.
var readyConditionTypes = sets.New(
	"Available",       // Deployment
	"ContainersReady", // Pod
	"Established",     // CustomResourceDefinition
	"Healthy",         // Commonly used by operators for custom resources
	"Initialized",     // Pod
	"NamesAccepted",   // CustomResourceDefinition
	"PodScheduled",    // Pod
	"Ready",           // Pod, Node, and the convention for custom resources
)

// readyConditionTypesByGroupKind lists additional readiness conditions that only carry their
// meaning for a specific kind, and would be ambiguous if applied to every object. They are
// honoured on top of readyConditionTypes for that kind alone.
var readyConditionTypesByGroupKind = map[schema.GroupKind]sets.Set[string]{
	// A Deployment reports "Progressing" as "False" when it gave up on a rollout, typically
	// with reason ProgressDeadlineExceeded. That can happen while the previous replica set
	// still serves traffic, so "Available" alone would report it as healthy.
	{Group: "apps", Kind: "Deployment"}: sets.New("Progressing"),
	// Gateway API resources signal readiness through "Accepted" and "Programmed" rather than
	// through a "Ready" condition.
	{Group: "gateway.networking.k8s.io", Kind: "Gateway"}:      sets.New("Accepted", "Programmed"),
	{Group: "gateway.networking.k8s.io", Kind: "GatewayClass"}: sets.New("Accepted"),
}

// isHealthy reports whether the object should be considered "healthy".
//
// This is a deliberately small set of heuristics: kinds with no readiness signal are assumed
// healthy, and otherwise readiness is read from the status conditions listed in
// readyConditionTypes and readyConditionTypesByGroupKind. The kstatus library implements a
// fuller version of this, should this ever need to grow much beyond the kinds kops applies.
func isHealthy(u *unstructured.Unstructured) bool {
	// Check if the resource is scheduled for deletion
	deletionTimestamp := u.GetDeletionTimestamp()
	if deletionTimestamp != nil {
		klog.Infof("object %s is scheduled for deletion", humanName(u))
		return false
	}

	gvk := u.GroupVersionKind()
	switch gvk {
	case schema.GroupVersionKind{Group: "", Version: "v1", Kind: "ConfigMap"},
		schema.GroupVersionKind{Group: "", Version: "v1", Kind: "ServiceAccount"},
		schema.GroupVersionKind{Group: "autoscaling", Version: "v1", Kind: "HorizontalPodAutoscaler"},
		schema.GroupVersionKind{Group: "autoscaling", Version: "v2", Kind: "HorizontalPodAutoscaler"}:
		// No ready signal; assume ready
		return true
	case schema.GroupVersionKind{Group: "rbac.authorization.k8s.io", Version: "v1", Kind: "ClusterRole"},
		schema.GroupVersionKind{Group: "rbac.authorization.k8s.io", Version: "v1", Kind: "ClusterRoleBinding"},
		schema.GroupVersionKind{Group: "rbac.authorization.k8s.io", Version: "v1", Kind: "Role"},
		schema.GroupVersionKind{Group: "rbac.authorization.k8s.io", Version: "v1", Kind: "RoleBinding"}:
		// No ready signal; assume ready
		return true
	case schema.GroupVersionKind{Group: "scheduling.k8s.io", Version: "v1", Kind: "PriorityClass"}:
		// No ready signal; assume ready
		return true
	case schema.GroupVersionKind{Group: "storage.k8s.io", Version: "v1", Kind: "StorageClass"}:
		// No ready signal; assume ready
		return true
	}

	// May be nil, which is fine: Has reports false for every type on a nil set.
	kindReadyConditionTypes := readyConditionTypesByGroupKind[gvk.GroupKind()]

	ready := true
	statusConditions, found, err := unstructured.NestedFieldNoCopy(u.Object, "status", "conditions")
	// CRDs may have status.conditions: null (found=true, value=nil); treat as absent.
	if err != nil || !found || statusConditions == nil {
		klog.Infof("status conditions not found for %s", humanName(u))
		return true
	}

	statusConditionsList, ok := statusConditions.([]interface{})
	if !ok {
		klog.Warningf("expected status.conditions to be list, got %T", statusConditions)
		return true
	}
	for i := range statusConditionsList {
		condition := statusConditionsList[i]
		conditionMap, ok := condition.(map[string]interface{})
		if !ok {
			klog.Warningf("expected status.conditions[%d] to be map, got %T", i, condition)
			return true
		}

		conditionType := ""
		conditionStatus := ""
		for k, v := range conditionMap {
			switch k {
			case "type":
				s, ok := v.(string)
				if !ok {
					klog.Warningf("expected status.conditions[].type to be string, got %T", v)
				} else {
					conditionType = s
				}
			case "status":
				s, ok := v.(string)
				if !ok {
					klog.Warningf("expected status.conditions[].status to be string, got %T", v)
				} else {
					conditionStatus = s
				}
			}
		}

		if !readyConditionTypes.Has(conditionType) && !kindReadyConditionTypes.Has(conditionType) {
			continue
		}

		switch conditionStatus {
		case "True":
			// ready

		case "False":
			j, _ := json.Marshal(condition)
			klog.Infof("status.conditions indicates object %s is not ready: %v", humanName(u), string(j))
			ready = false

		case "":
			klog.Warningf("ignoring status.conditions[] type %q with unknown status %q", conditionType, conditionStatus)
		}
	}

	if !ready {
		klog.Infof("object %s is not ready", humanName(u))
	}
	return ready
}

// humanName returns an identifier for the object suitable for printing in log messages
func humanName(u *unstructured.Unstructured) string {
	gvk := u.GroupVersionKind()
	var s strings.Builder
	s.WriteString(gvk.Kind)
	if gvk.Group != "" {
		s.WriteString(".")
		s.WriteString(gvk.Group)
	}
	s.WriteString(":")
	namespace := u.GetNamespace()
	name := u.GetName()
	if namespace != "" {
		s.WriteString(namespace)
		s.WriteString("/")
		s.WriteString(name)
	} else {
		s.WriteString(name)
	}
	return s.String()
}
