package main

import (
	"flag"
	"log"
	"net"

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

func main() {
	listenAddr := flag.String("listen", ":9000", "server listen address") //监听地址
	logPath := flag.String("latency-log", "", "optional JSONL file path for latency timestamp logs")
	flag.Parse() //查看命令行参数

	hubOptions := make([]server.Option, 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.WithLogger(logger))
	}

	listener, err := net.Listen("tcp", *listenAddr) //开启tcp监听器，监听来自客户端的连接请求
	if err != nil {
		log.Fatalf("listen on %s: %v", *listenAddr, err)
	}
	defer listener.Close() //确保在 main 函数退出时关闭监听器

	hub := server.NewHub(hubOptions...) //创建一个新的 Hub 实例，负责管理客户端连接和消息转发
	log.Printf("server listening on %s", listener.Addr())

	for {
		conn, err := listener.Accept()
		if err != nil {
			log.Printf("accept connection: %v", err)
			continue
		}

		go func(rawConn net.Conn) {
			if err := hub.ServeConn(rawConn); err != nil {
				log.Printf("connection closed: %v", err)
			}
		}(conn)
	}
}
