package transport

import (
	"encoding/json"
	"log"
	"net"

	"github.com/user/nanometrics/server/models"
)

func StartUDP(addr string, handler func(*models.AgentMetrics)) error {
	conn, err := net.ListenPacket("udp", addr)
	if err != nil {
		return err
	}
	log.Printf("[udp] écoute sur %s", addr)
	go func() {
		buf := make([]byte, 65535)
		for {
			n, _, err := conn.ReadFrom(buf)
			if err != nil {
				log.Printf("[udp] erreur lecture: %v", err)
				continue
			}
			data := make([]byte, n)
			copy(data, buf[:n])
			go processUDP(data, handler)
		}
	}()
	return nil
}

func processUDP(data []byte, handler func(*models.AgentMetrics)) {
	var m models.AgentMetrics
	if err := json.Unmarshal(data, &m); err != nil {
		log.Printf("[udp] JSON invalide: %v", err)
		return
	}
	if m.Hostname == "" {
		return
	}
	handler(&m)
}
