/*
Copyright 2022.

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 controllers

import (
	"bytes"
	"context"
	"fmt"
	corev1 "k8s.io/api/core/v1"
	"k8s.io/apimachinery/pkg/labels"
	"os"
	"strings"
	"time"

	"github.com/mattn/go-shellwords"
	"github.com/spf13/cobra"
	"github.com/tikv/pd/tools/pd-ctl/pdctl/command"

	"k8s.io/apimachinery/pkg/runtime"
	ctrl "sigs.k8s.io/controller-runtime"
	"sigs.k8s.io/controller-runtime/pkg/client"
	"sigs.k8s.io/controller-runtime/pkg/log"

	cloudv1 "github.com/tidbcloud/operationlet/api/v1"
)

const (
	timeout = 20 * time.Minute
	PD      = "pd"
	TIDB    = "tidb"
	TIKV    = "tikv"
	PD_PORT = "2379"
)

// OperationProxyServiceReconciler reconciles a OperationProxyService object
type OperationProxyServiceReconciler struct {
	client.Client
	Scheme *runtime.Scheme
}

//+kubebuilder:rbac:groups=cloud.cloud.pingcap.com,resources=operationproxyservices,verbs=get;list;watch;create;update;patch;delete
//+kubebuilder:rbac:groups=cloud.cloud.pingcap.com,resources=operationproxyservices/status,verbs=get;update;patch
//+kubebuilder:rbac:groups=cloud.cloud.pingcap.com,resources=operationproxyservices/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.
// TODO(user): Modify the Reconcile function to compare the state specified by
// the OperationProxyService object against the actual cluster state, and then
// perform operations to make the cluster state reflect the state specified by
// the user.
//
// For more details, check Reconcile and its Result here:
// - https://pkg.go.dev/sigs.k8s.io/controller-runtime@v0.8.3/pkg/reconcile
func (r *OperationProxyServiceReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {
	var err error
	logger := log.FromContext(ctx)

	job := &cloudv1.OperationProxyService{}
	if err := r.Get(ctx, req.NamespacedName, job); err != nil {
		return ctrl.Result{}, client.IgnoreNotFound(err)
	}
	// your logic here
	logger.Info("Watch the ProxyJob!")

	if job.Status.Phase == "" {
		if err := r.transToStatus(ctx, job, cloudv1.JobPhaseWaiting); err != nil {
			return ctrl.Result{}, err
		}
	}
	logger.Info("Watch proxy job!.",
		"instance", job.Spec.Instance,
		"cluster_id", job.Spec.ClusterID,
		"tenant_id", job.Spec.TenantID)

	switch job.Status.Phase {
	case cloudv1.JobPhaseWaiting:
		err = r.observeProxyCmd(ctx, job)
	case cloudv1.JobPhasePending:
		err = r.runProxyCmd(ctx, job)
	case cloudv1.JobPhaseRunning:
		err = r.observeProxyCmd(ctx, job)
	}
	return ctrl.Result{Requeue: true}, err
}

// SetupWithManager sets up the controller with the Manager.
func (r *OperationProxyServiceReconciler) SetupWithManager(mgr ctrl.Manager) error {
	return ctrl.NewControllerManagedBy(mgr).
		For(&cloudv1.OperationProxyService{}).
		Complete(r)
}

// runProxyCmd run a pd-ctl client.
func (r *OperationProxyServiceReconciler) runProxyCmd(ctx context.Context, job *cloudv1.OperationProxyService) error {
	var err error
	logger := log.FromContext(ctx)
	defer func() {
		if err != nil {
			logger.Error(err, "run job failed", "jobName", job.Name, "cluster_id", job.Spec.ClusterID)
			if err = r.transToStatus(ctx, job, cloudv1.JobPhaseFailed); err != nil {
				logger.Error(err, "update job status failed", "jobName", job.Name, "cluster_id", job.Spec.ClusterID)
			}
		}
	}()
	selector, _ := labels.Parse(fmt.Sprintf("app.kubernetes.io/instance=%s", job.Spec.Instance))
	option := &client.ListOptions{
		LabelSelector: selector,
		Namespace:     NamespacePrefix + job.Spec.ClusterID,
		Limit:         1,
	}
	var podList corev1.PodList
	err = r.Client.List(ctx, &podList, option)
	if err != nil || len(podList.Items) == 0 {
		logger.Info("Failed to list instance or no instance")
		return err
	}
	pod := podList.Items[0]
	pdUrl := fmt.Sprintf("https://%s.%s-%s-peer.%s:%s", pod.Name, job.Spec.Instance, PD, pod.Namespace, PD_PORT)
	job.Status.Result = run(ctx, pdUrl, job.Spec.Command)
	if err = r.Status().Update(ctx, job); err != nil {
		logger.Info("Failed to update job status")
		return err
	}
	return r.transToStatus(ctx, job, cloudv1.JobPhaseSuccess)
}

// observeProxyCmd observes the cmd have time out or not.
func (r *OperationProxyServiceReconciler) observeProxyCmd(ctx context.Context, job *cloudv1.OperationProxyService) error {
	logger := log.FromContext(ctx)
	switch job.Status.Phase {
	case cloudv1.JobPhaseWaiting:
		logger.Info("Waiting for the proxy job to start")
	case cloudv1.JobPhaseRunning:
		logger.Info("check the pd proxy job timeout or not.", "cluster_id", job.Spec.ClusterID, "email", job.Spec.Email)
		if job.Status.Phase != cloudv1.JobPhaseWaiting && job.GetCreationTimestamp().Unix()+int64(timeout.Seconds()) < time.Now().Unix() {
			logger.Info("PD proxy job timeout", "instance", job.Spec.Instance,
				"cluster_id", job.Spec.ClusterID,
				"tenant_id", job.Spec.TenantID,
				"phase", job.Status.Phase,
				"email", job.Spec.Email)
			newStatus := cloudv1.JobPhaseSuccess
			if job.Status.Phase != cloudv1.JobPhaseRunning {
				newStatus = cloudv1.JobPhaseFailed
			}
			if err := r.transToStatus(ctx, job, newStatus); err != nil {
				return err
			}
		}
	}
	return nil
}

func run(ctx context.Context, pdUrl, command string) string {
	logger := log.FromContext(ctx)
	buf := new(bytes.Buffer)
	getREPLCmd := func() *cobra.Command {
		rootCmd := GetRootCommand(pdUrl)
		rootCmd.SetOut(os.Stdout)
		return rootCmd
	}
	if strings.ToLower(command) == "exit" {
		logger.Info("Exit!")
		os.Exit(0)
	}
	args, err := shellwords.Parse(command)
	if err != nil {
		return fmt.Sprintf("parse command err: %v\n", err)
	}
	rootCmd := getREPLCmd()
	rootCmd.SetArgs(args)
	rootCmd.ParseFlags(args)
	rootCmd.SetOut(buf)
	rootCmd.Execute()
	return buf.String()

}

func GetRootCommand(pdUrl string) *cobra.Command {
	rootCmd := &cobra.Command{
		Use:   "pdctl",
		Short: "Placement Driver control",
	}
	rootCmd.PersistentFlags().StringVarP(&pdUrl, "pd", "u", pdUrl, "pd address")
	rootCmd.AddCommand(
		command.NewConfigCommand(),
		command.NewRegionCommand(),
		command.NewStoreCommand(),
		command.NewStoresCommand(),
		command.NewMemberCommand(),
		command.NewExitCommand(),
		command.NewLabelCommand(),
		command.NewPingCommand(),
		command.NewOperatorCommand(),
		command.NewSchedulerCommand(),
		command.NewTSOCommand(),
		command.NewHotSpotCommand(),
		command.NewClusterCommand(),
		command.NewTableNamespaceCommand(),
		command.NewHealthCommand(),
	)
	return rootCmd
}

func (r *OperationProxyServiceReconciler) transToStatus(ctx context.Context, job *cloudv1.OperationProxyService, newStatus cloudv1.CommandJobPhase) error {
	var err error
	logger := log.FromContext(ctx)
	if job.Status.Phase != newStatus {
		logger.Info("command job update status", "jobName", job.Name,
			"oldStatus", string(job.Status.Phase),
			"newStatus", string(newStatus))
		job.Status.Phase = newStatus
		err = r.Status().Update(ctx, job)
	}
	return err
}
