package main

import (
	"context"
	"os"
	"time"

	v1alpha1 "github.com/pfeifferj/container-mom-go/pkg/apis/containermom/v1alpha1"
	"k8s.io/apimachinery/pkg/runtime"
	clientgoscheme "k8s.io/client-go/kubernetes/scheme"
	"k8s.io/client-go/rest"
	ctrl "sigs.k8s.io/controller-runtime"
	"sigs.k8s.io/controller-runtime/pkg/client"
	"sigs.k8s.io/controller-runtime/pkg/client/config"
	"sigs.k8s.io/controller-runtime/pkg/manager"
	"sigs.k8s.io/controller-runtime/pkg/reconcile"
)

var scheme = runtime.NewScheme()

func init() {
	_ = clientgoscheme.AddToScheme(scheme)
	_ = v1alpha1.AddToScheme(scheme)
}

func main() {
	ctx := context.Background()
	ctrl.SetLogger(ctrl.Log.WithName("test-wlc"))

	ctrl.Log.Info("Starting test program")

	// Get config from kubeconfig
	cfg := config.GetConfigOrDie()

	// Create a client
	k8sClient, err := client.New(cfg, client.Options{Scheme: scheme})
	if err != nil {
		ctrl.Log.Error(err, "failed to create client")
		os.Exit(1)
	}

	// Get the CR
	cr := &v1alpha1.ContainerMomDeployment{}
	err = k8sClient.Get(ctx, client.ObjectKey{Name: "josie-lol", Namespace: "container-mom-system"}, cr)
	if err != nil {
		ctrl.Log.Error(err, "failed to get CR")
		os.Exit(1)
	}

	ctrl.Log.Info("Found CR", "name", cr.Name, "clusters", cr.Spec.Clusters)

	// Create manager
	mgr, err := manager.New(cfg, manager.Options{
		Scheme: scheme,
	})
	if err != nil {
		ctrl.Log.Error(err, "failed to create manager")
		os.Exit(1)
	}

	// Load local cluster only
	clusterConfigs := make(map[string]*rest.Config)
	clusterConfigs["local"] = cfg

	// Start the manager and wait to connect
	stopCh := ctrl.SetupSignalHandler()
	go func() {
		if err := mgr.Start(stopCh); err != nil {
			ctrl.Log.Error(err, "failed to start manager")
			os.Exit(1)
		}
	}()

	// Wait for manager to start
	time.Sleep(5 * time.Second)

	// Force a reconciliation on the "josie-lol" CR
	request := reconcile.Request{
		NamespacedName: client.ObjectKey{
			Name:      "josie-lol",
			Namespace: "container-mom-system",
		},
	}

	ctrl.Log.Info("Forcing reconciliation of CR", "name", request.Name, "namespace", request.Namespace)

	// Force manager to update controller cache
	time.Sleep(5 * time.Second)

	ctrl.Log.Info("Test completed, check for namespace creation")
}
