/*
Copyright 2021.

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 tiflow

import (
	"context"
	"fmt"
	"time"

	corev1 "k8s.io/api/core/v1"
	apierrors "k8s.io/apimachinery/pkg/api/errors"
	"k8s.io/apimachinery/pkg/types"
	ctrl "sigs.k8s.io/controller-runtime"
	"sigs.k8s.io/controller-runtime/pkg/builder"
	"sigs.k8s.io/controller-runtime/pkg/client"
	"sigs.k8s.io/controller-runtime/pkg/controller"
	"sigs.k8s.io/controller-runtime/pkg/controller/controllerutil"
	"sigs.k8s.io/controller-runtime/pkg/log"
	"sigs.k8s.io/controller-runtime/pkg/predicate"

	eksv1alpha1 "github.com/tidbcloud/eks-provider/api/v1alpha1"
	"github.com/tidbcloud/eks-provider/controllers/tiflow/config/component"
	"github.com/tidbcloud/eks-provider/controllers/tiflow/spec"
	"github.com/tidbcloud/eks-provider/controllers/tiflow/task"
	"github.com/tidbcloud/eks-provider/controllers/tiflow/task/cluster"
	clustereks "github.com/tidbcloud/eks-provider/controllers/tiflow/task/cluster/eks"
	"github.com/tidbcloud/eks-provider/controllers/tiflow/task/cluster/executor"
	"github.com/tidbcloud/eks-provider/controllers/tiflow/task/cluster/executor/eks"
	"github.com/tidbcloud/eks-provider/controllers/tiflow/task/cluster/executor/gke"
	clustergke "github.com/tidbcloud/eks-provider/controllers/tiflow/task/cluster/gke"
	cloudv1 "github.com/tidbcloud/infra-api/api/v1"
	"github.com/tidbcloud/infra-provider/pkg/config"
	"github.com/tidbcloud/infra-provider/pkg/consts"
	"github.com/tidbcloud/infra-provider/pkg/controllers/common"
	"github.com/tidbcloud/infra-provider/pkg/deploy"
	metricsctrl "github.com/tidbcloud/infra-provider/pkg/metrics/controller"
	"github.com/tidbcloud/infra-provider/pkg/procedure"
)

// TiflowClusterExecutorReconciler reconciles a TiflowClusterExecutor object
type TiflowClusterExecutorReconciler struct {
	BaseTiflowReconciler
}

func NewTiflowClusterExecutorReconciler(mgr ctrl.Manager, infraCli client.Client, infraReader client.Reader, config config.RootConfig, svc procedure.AWSService) *TiflowClusterExecutorReconciler {
	tiflowClusterExecutorReconciler := &TiflowClusterExecutorReconciler{
		BaseTiflowReconciler: BaseTiflowReconciler{
			Scheme:        mgr.GetScheme(),
			Local:         infraCli,
			Logger:        ctrl.Log.WithName("controllers").WithName("TiflowClusterExecutor"),
			Config:        config,
			Cache:         infraReader,
			EventRecorder: mgr.GetEventRecorderFor("tiflow-cluster-executor-controller"),
			AWSSVC:        svc,
		},
	}
	return tiflowClusterExecutorReconciler
}

//+kubebuilder:rbac:groups=eks.infra.pingcap.com,resources=tiflowclusterexecutors,verbs=get;list;watch;create;update;patch;delete
//+kubebuilder:rbac:groups=eks.infra.pingcap.com,resources=tiflowclusterexecutors/status,verbs=get;update;patch
//+kubebuilder:rbac:groups=eks.infra.pingcap.com,resources=tiflowclusterexecutors/finalizers,verbs=update

// Reconcile is part of the main kubernetes reconciliation loop which aims to
// move the current state of the cluster closer to the desired state.
//
// For more details, check Reconcile and its Result here:
// - https://pkg.go.dev/sigs.k8s.io/controller-runtime@v0.12.2/pkg/reconcile
func (r *TiflowClusterExecutorReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {
	log := r.Logger.WithValues("object", req.NamespacedName)
	log.Info("Reconciling Tiflow Cluster Executor")
	start := time.Now()
	defer func() {
		metricsctrl.ReconcileDuration.
			WithLabelValues("tiflow_cluster_executor").Observe(time.Since(start).Seconds())
		log.Info("Finish tiflow cluster executor reconcile", "take", time.Since(start))
	}()

	tiflowClusterExecutor := &eksv1alpha1.TiflowClusterExecutor{}
	if err := r.Cache.Get(ctx, req.NamespacedName, tiflowClusterExecutor); err != nil {
		if apierrors.IsNotFound(err) {
			return ctrl.Result{}, nil
		}
		return ctrl.Result{}, fmt.Errorf("unable to get tiflow cluster executor %s: %v", req.NamespacedName, err)
	}

	c, err := r.buildContext(ctx, tiflowClusterExecutor)
	if err != nil {
		r.Logger.Error(err, "unable to build context for tiflow cluster executor", "name", req.NamespacedName)
		return ctrl.Result{RequeueAfter: time.Minute * 1}, nil
	}

	tasks := r.buildTaskGroup(c)
	d := deploy.NewDeployer(tasks, nil, r.Logger)
	var res ctrl.Result
	if tiflowClusterExecutor.DeletionTimestamp.IsZero() {
		res, err = r.updateCreate(ctx, c, d.Deploy(ctx))
	} else {
		res, err = r.updateDelete(ctx, c, d.Destroy(ctx))
	}

	if err == nil {
		r.EventRecorder.Event(tiflowClusterExecutor, corev1.EventTypeNormal, "ReconcileSuccess", "")
	} else {
		r.EventRecorder.Event(tiflowClusterExecutor, corev1.EventTypeWarning, "ReconcileFail", err.Error())
	}
	return res, err
}

func (r *TiflowClusterExecutorReconciler) buildContext(ctx context.Context, tiflowClusterExecutor *eksv1alpha1.TiflowClusterExecutor) (*executor.Context, error) {
	network, err := r.QueryNetworkInfo(ctx, tiflowClusterExecutor.Namespace, tiflowClusterExecutor.Spec.NetworkName)
	if err != nil {
		return nil, err
	}

	provider, err := r.QueryProvider(ctx, network.Spec.Provider)
	if err != nil {
		return nil, err
	}

	tiflowSpec, err := r.CheckAndGetExecutorSpecCode(ctx, network, tiflowClusterExecutor.Spec.SpecCode)
	if err != nil {
		return nil, err
	}

	c := (&executor.Context{
		BaseContext: &cluster.BaseContext{
			Local:      r.Local,
			Config:     r.Config,
			Network:    network,
			Logger:     r.Logger,
			TiflowSpec: tiflowSpec,
			Provider:   provider,
			AWSSVC:     r.AWSSVC,
			GCP:        r.GCP,
		},
		TiflowClusterExecutor: tiflowClusterExecutor,
	}).Default()

	// NOTE: if we meet error here, DON'T return error
	// leave the tiflowclustermaster task reports this error
	cc, err := component.NewExecutorConfigQuirer(c).Execute(ctx)
	if err == nil {
		c.ClusterConfig = cc
	} else {
		r.Logger.Error(err, "get master config error")
	}

	err = c.SetRemoteClient(ctx)
	if err != nil {
		// DON'T return error here, or it will block the deletion of object
		// If we get any error here, tasks will report error since the default
		// getter is an empty getter
		r.Logger.Error(err, "fail to set remote client")
	}

	return c, nil
}

func (r *TiflowClusterExecutorReconciler) buildTaskGroup(c *executor.Context) []deploy.Task {
	tiDBClusterName := spec.GetTiDBClusterName(&c.TiflowClusterExecutor.ObjectMeta)
	objCond := &c.TiflowClusterExecutor.Status.Conditions

	if r.Config.Predicate.MatchLabels[cloudv1.ProviderTypeLabel] == consts.ProviderTypeGKE {
		return []deploy.Task{
			executor.NewGuardian(c),
			executor.NewExecutorPhase(c),
			clustergke.NewNodePool(c.BaseContext, tiDBClusterName, objCond),
			gke.NewTiflowClusterExecutor(c),
			clustergke.NewNodeGroupGC(c.BaseContext, objCond),
		}
	}

	return []deploy.Task{
		executor.NewGuardian(c),
		executor.NewExecutorPhase(c),
		clustereks.NewNodeGroup(c.BaseContext, tiDBClusterName, objCond),
		eks.NewTiflowClusterExecutor(c),
		clustereks.NewNodeGroupGC(c.BaseContext, objCond),
	}
}

func (r *TiflowClusterExecutorReconciler) updateCreate(ctx context.Context, t *executor.Context, results []deploy.Result) (res ctrl.Result, err error) {
	res, err, retriableErrs := deploy.MinRequeue(results)
	switch phase := t.TiflowClusterExecutor.Status.Phase; phase {
	case eksv1alpha1.TiflowClusterExecutorPhaseCreating:
		if err == nil && retriableErrs == nil {
			log.FromContext(ctx).Info("mark tiflow cluster executor become running when creating cluster",
				"sinceCreate", time.Since(t.TiflowClusterExecutor.CreationTimestamp.Time))
			t.TiflowClusterExecutor.Status.Phase = eksv1alpha1.TiflowClusterExecutorPhaseRunning
		}
	default:
	}
	if err := r.update(ctx, t.Local, t.TiflowClusterExecutor); err != nil {
		return res, err
	}
	return
}

func (r *TiflowClusterExecutorReconciler) updateDelete(ctx context.Context, t *executor.Context, results []deploy.Result) (res ctrl.Result, err error) {
	// If the cluster is pending delete, then the deletion tasks are not actually performed
	res, err, retriableErrs := deploy.MinRequeue(results)
	switch phase := t.TiflowClusterExecutor.Status.Phase; phase {
	case eksv1alpha1.TiflowClusterExecutorPhaseDeleting:
		if err == nil && retriableErrs == nil {
			controllerutil.RemoveFinalizer(t.TiflowClusterExecutor, task.Finalizer)
		}
	default:
	}
	if err := r.update(ctx, t.Local, t.TiflowClusterExecutor); err != nil {
		return res, err
	}
	return
}

func (r *TiflowClusterExecutorReconciler) update(ctx context.Context, cli client.Client, tiflowClusterExecutor *eksv1alpha1.TiflowClusterExecutor) error {
	tiflowClusterStatus := tiflowClusterExecutor.Status.DeepCopy()
	if err := cli.Update(ctx, tiflowClusterExecutor); err != nil {
		return err
	}
	if err := cli.Get(ctx, types.NamespacedName{Name: tiflowClusterExecutor.Name, Namespace: tiflowClusterExecutor.Namespace}, tiflowClusterExecutor); err != nil {
		return err
	}
	tiflowClusterExecutor.Status = *tiflowClusterStatus
	return cli.Status().Update(ctx, tiflowClusterExecutor)
}

// SetupWithManager sets up the controller with the Manager.
func (r *TiflowClusterExecutorReconciler) SetupWithManager(mgr ctrl.Manager, p ...predicate.Predicate) error {
	return ctrl.NewControllerManagedBy(mgr).
		For(&eksv1alpha1.TiflowClusterExecutor{}, builder.WithPredicates(p...)).
		WithOptions(controller.Options{RateLimiter: common.DefaultRateLimiter(), MaxConcurrentReconciles: 10}).
		Complete(r)
}
