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, src, 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, src.String(), handler)
		}
	}()
	return nil
}

func processUDP(data []byte, src string, handler func(*models.AgentMetrics)) {
	var m models.AgentMetrics
	if err := json.Unmarshal(data, &m); err != nil {
		end := 32
		if len(data) < end {
			end = len(data)
		}
		log.Printf("[udp] JSON invalide: %v | src=%s | octets: %x", err, src, data[:end])
		return
	}
	if m.Hostname == "" {
		return
	}
	// DEBUG SMART — logguer le payload ASUS complet
	if m.Smart != nil {
		log.Printf("[udp] SMART reçu de %s: %d disque(s)", m.Hostname, len(m.Smart))
	} else {
		log.Printf("[udp] payload de %s (v%s): smart=nil hdd=%v", m.Hostname, m.Version, m.HDDTotal)
	}
	handler(&m)
}
