package p2p

import (
	"context"
	"fmt"
	"time"

	dht "github.com/libp2p/go-libp2p-kad-dht"
	routingdiscovery "github.com/libp2p/go-libp2p/p2p/discovery/routing"
)

const rendezvousString = "dejo-global"

// InitDHT inicializa o Kademlia DHT e ativa descoberta global de peers.
func (p *P2PNode) InitDHT(ctx context.Context) error {
	d, err := dht.New(ctx, p.Host)
	if err != nil {
		return fmt.Errorf("erro ao iniciar DHT: %w", err)
	}

	if err := d.Bootstrap(ctx); err != nil {
		return fmt.Errorf("erro ao bootstrap DHT: %w", err)
	}

	routing := routingdiscovery.NewRoutingDiscovery(d)
	_, err = routing.Advertise(ctx, rendezvousString)
	if err != nil {
		return fmt.Errorf("erro ao anunciar no DHT: %w", err)
	}

	fmt.Println("📡 Anunciado no DHT com tag:", rendezvousString)

	go func() {
		for {
			peers, err := routing.FindPeers(ctx, rendezvousString)
			if err != nil {
				fmt.Println("Erro ao buscar peers:", err)
				continue
			}
			for pinfo := range peers {
				if pinfo.ID == p.Host.ID() {
					continue // ignora si mesmo
				}
				fmt.Println("🌍 Peer encontrado via DHT:", pinfo.ID)
				_ = p.Host.Connect(ctx, pinfo)
			}
			time.Sleep(10 * time.Second)
		}
	}()

	return nil
}