package main

import (
	"context"
	"os"
	"time"

	v1alpha1 "github.com/pfeifferj/container-mom-go/pkg/apis/containermom/v1alpha1"
	"github.com/pfeifferj/container-mom-go/pkg/operator"
	"k8s.io/apimachinery/pkg/runtime"
	clientgoscheme "k8s.io/client-go/kubernetes/scheme"
	"k8s.io/client-go/tools/clientcmd"
	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"
)

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]*clientcmd.RestConfig)
	clusterConfigs["local"] = cfg

	ctrl.Log.Info("Creating workload controller")
	// Initialize the workload controller
	if err := operator.NewWorkloadController(mgr, clusterConfigs); err != nil {
		ctrl.Log.Error(err, "failed to create workload controller")
		os.Exit(1)
	}

	// Start manager in a goroutine
	go func() {
		ctrl.Log.Info("Starting manager")
		if err := mgr.Start(ctx); err != nil {
			ctrl.Log.Error(err, "failed to start manager")
			os.Exit(1)
		}
	}()

	// Wait a bit for controller to start
	time.Sleep(2 * time.Second)

	// Create a test request for reconciliation
	req := ctrl.Request{
		NamespacedName: client.ObjectKey{
			Name:      "josie-lol",
			Namespace: "container-mom-system",
		},
	}

	// Create controller manually
	controller := &operator.WorkloadController{
		Client:   mgr.GetClient(),
		Scheme:   mgr.GetScheme(),
		Clusters: make(map[string]ctrl.Cluster),
	}

	// Add local cluster
	controller.Clusters["local"] = nil // Just a placeholder

	// Call reconcile directly
	ctrl.Log.Info("Calling reconcile directly")
	result, err := controller.Reconcile(ctx, req)
	if err != nil {
		ctrl.Log.Error(err, "reconcile failed")
	} else {
		ctrl.Log.Info("Reconcile succeeded", "result", result)
	}

	// Wait for logs to flush
	time.Sleep(5 * time.Second)
}
