package main

import (
	"log"

	"git.tornberg.me/go-cart-actor/pkg/actor"
	"git.tornberg.me/go-cart-actor/pkg/cart"
	"git.tornberg.me/go-cart-actor/pkg/discovery"
	"k8s.io/client-go/kubernetes"
	"k8s.io/client-go/rest"
)

func GetDiscovery() discovery.Discovery {
	if podIp == "" {
		return nil
	}

	config, kerr := rest.InClusterConfig()

	if kerr != nil {
		log.Fatalf("Error creating kubernetes client: %v\n", kerr)
	}
	client, err := kubernetes.NewForConfig(config)
	if err != nil {
		log.Fatalf("Error creating client: %v\n", err)
	}
	return discovery.NewK8sDiscovery(client)
}

func UseDiscovery(pool actor.GrainPool[*cart.CartGrain]) {

	go func(hw discovery.Discovery) {
		if hw == nil {
			log.Print("No discovery service available")
			return
		}
		ch, err := hw.Watch()
		if err != nil {
			log.Printf("Discovery error: %v", err)
			return
		}
		for evt := range ch {
			if evt.Host == "" {
				continue
			}
			switch evt.IsReady {
			case false:
				if pool.IsKnown(evt.Host) {
					log.Printf("Host %s is not ready, removing", evt.Host)
					pool.RemoveHost(evt.Host)
				}
			default:
				if !pool.IsKnown(evt.Host) {
					log.Printf("Discovered host %s", evt.Host)
					pool.AddRemoteHost(evt.Host)
				}
			}
		}
	}(GetDiscovery())
}
