package main

import (
	"flag"
	"log"
	"net"

	"omnisocketgo/cmd/internal/latencylog"
	"omnisocketgo/cmd/internal/server"
)

func main() {
	listenAddr := flag.String("listen", ":9001", "UDP server listen address")
	logPath := flag.String("latency-log", "", "optional JSONL file path for latency timestamp logs")
	flag.Parse()

	hubOptions := make([]server.UDPOption, 0, 1)
	if *logPath != "" {
		logger, err := latencylog.NewJSONLLogger(*logPath)
		if err != nil {
			log.Fatalf("create latency logger %s: %v", *logPath, err)
		}
		defer logger.Close()
		hubOptions = append(hubOptions, server.WithUDPLogger(logger))
	}

	udpAddr, err := net.ResolveUDPAddr("udp", *listenAddr)
	if err != nil {
		log.Fatalf("resolve udp address %s: %v", *listenAddr, err)
	}

	conn, err := net.ListenUDP("udp", udpAddr)
	if err != nil {
		log.Fatalf("listen udp on %s: %v", *listenAddr, err)
	}
	defer conn.Close()

	hub, err := server.NewUDPHub(conn, hubOptions...)
	if err != nil {
		log.Fatalf("create udp hub: %v", err)
	}

	log.Printf("udp server listening on %s", conn.LocalAddr())

	if err := hub.Serve(); err != nil {
		log.Fatalf("udp hub serve: %v", err)
	}
}
