package main

import (
	"context"
	"flag"
	"net/http"
	"net/http/pprof"
	"os"

	"go.uber.org/zap/zapcore"
	"k8s.io/apimachinery/pkg/runtime"
	utilruntime "k8s.io/apimachinery/pkg/util/runtime"
	clientgoscheme "k8s.io/client-go/kubernetes/scheme"
	_ "k8s.io/client-go/plugin/pkg/client/auth" // Import all Kubernetes client auth plugins (e.g. Azure, GCP, OIDC, etc.) to ensure that exec-entrypoint and run can make use of them.
	ctrl "sigs.k8s.io/controller-runtime"
	"sigs.k8s.io/controller-runtime/pkg/cache"
	"sigs.k8s.io/controller-runtime/pkg/client"
	"sigs.k8s.io/controller-runtime/pkg/healthz"
	"sigs.k8s.io/controller-runtime/pkg/log/zap"
	metricsserver "sigs.k8s.io/controller-runtime/pkg/metrics/server"
	"sigs.k8s.io/controller-runtime/pkg/webhook"

	cloudv1 "github.com/tidbcloud/infra-api/api/v1"
	compatk8s "github.com/tidbcloud/infra-provider/pkg/compat/k8s"
	pkgconfig "github.com/tidbcloud/infra-provider/pkg/config"
	"github.com/tidbcloud/tiinf/transport/crossregion"
)

var (
	scheme      = runtime.NewScheme()
	setupLog    = ctrl.Log.WithName("setup")
	metricsAddr string
	probeAddr   string
	pprofActive bool
	namespace   string
	comaptMode  bool
	compatEnv   string
)

func init() {
	utilruntime.Must(clientgoscheme.AddToScheme(scheme))
	utilruntime.Must(cloudv1.AddToScheme(scheme))
}

func main() {
	flag.StringVar(&metricsAddr, "metrics-bind-address", ":8080", "The address the metric endpoint binds to.")
	flag.BoolVar(&pprofActive, "pprof", true, "Enable pprof endpoint")
	flag.StringVar(&probeAddr, "health-probe-bind-address", ":8081", "The address the probe endpoint binds to.")
	flag.StringVar(&namespace, "namespace", "", "Namespace if specified restricts the manager's cache to watch objects in the desired namespace.")
	flag.BoolVar(&comaptMode, "compat-mode", false, "Enable compatibility mode")
	flag.StringVar(&compatEnv, "compat-env", "dev", "Compatibility environment")
	opts := zap.Options{
		Development: true,
		TimeEncoder: zapcore.RFC3339TimeEncoder,
	}
	opts.BindFlags(flag.CommandLine)
	flag.Parse()

	ctrl.SetLogger(zap.New(zap.UseFlagOptions(&opts)))

	// handlers set in pprof.init()
	handlers := map[string]http.Handler{}
	if pprofActive {
		handlers = map[string]http.Handler{
			"/debug/pprof/":        http.HandlerFunc(pprof.Index),
			"/debug/pprof/cmdline": http.HandlerFunc(pprof.Cmdline),
			"/debug/pprof/profile": http.HandlerFunc(pprof.Profile),
			"/debug/pprof/symbol":  http.HandlerFunc(pprof.Symbol),
			"/debug/pprof/trace":   http.HandlerFunc(pprof.Trace),
		}
	}

	options := ctrl.Options{
		Scheme: scheme,
		Metrics: metricsserver.Options{
			BindAddress:   metricsAddr,
			ExtraHandlers: handlers,
		},
		WebhookServer: webhook.NewServer(webhook.Options{
			Port: 9443,
		}),
		HealthProbeBindAddress: probeAddr,
		LeaderElection:         false, // we don't need leader election for webhook server
		Cache: cache.Options{
			DefaultNamespaces: map[string]cache.Config{
				namespace: {},
			},
		},
	}

	mgr, err := ctrl.NewManager(ctrl.GetConfigOrDie(), options)
	if err != nil {
		setupLog.Error(err, "unable to create manager")
		os.Exit(1)
	}

	if err = cloudv1.RegisterWebhooks(mgr); err != nil {
		setupLog.Error(err, "unable to register webhooks")
		os.Exit(1)
	}
	setupLog.Info("compat mode info:", "compat-mode", comaptMode, "compat-env", compatEnv)
	// if compatMode is enabled, we need to override the client and reader for webhooks
	if comaptMode {
		// in webhooks.we don't need to access dataplane,so we don't need to pass dataplane role arn
		infraCli := compatk8s.NewCompatK8sClient(mgr.GetClient(), crossregion.EnvType(compatEnv), "", "", "", pkgconfig.OverrideConfig{}, "")
		infraReader := compatk8s.NewCompatK8sReader(mgr.GetAPIReader(), crossregion.EnvType(compatEnv), "", "", "", pkgconfig.OverrideConfig{}, "")
		cloudv1.OverrideWebhookClient(infraCli, infraReader)
	}

	if err := mgr.GetFieldIndexer().IndexField(context.TODO(), &cloudv1.Network{}, "spec.region", func(obj client.Object) []string {
		n := obj.(*cloudv1.Network)
		return []string{n.Spec.Region}
	}); err != nil {
		setupLog.Error(err, "unable to add index field for network spec.region")
		os.Exit(1)
	}

	if err := mgr.AddHealthzCheck("healthz", healthz.Ping); err != nil {
		setupLog.Error(err, "unable to set up health check")
		os.Exit(1)
	}
	if err := mgr.AddReadyzCheck("readyz", healthz.Ping); err != nil {
		setupLog.Error(err, "unable to set up ready check")
		os.Exit(1)
	}

	ctx := ctrl.SetupSignalHandler()

	setupLog.Info("starting manager")
	if err := mgr.Start(ctx); err != nil {
		setupLog.Error(err, "problem running manager")
		os.Exit(1)
	}
}
