package main

import (
	"flag"
	"fmt"
	"log"
	"sync"
)

func main() {
	serverType := flag.String("server", "tcp", "服务器类型: tcp 或 udp")
	tcpPort := flag.String("tcpport", "10002", "TCP服务器端口")
	udpPort := flag.String("udpport", "10002", "UDP服务器端口")
	httpPort := flag.String("httpport", "10001", "HTTP服务器端口")
	flag.Parse()

	if err := InitLogger(); err != nil {
		log.Fatalf("初始化日志系统失败: %v", err)
	}
	defer CloseLogger()
	StartLogRotation()

	err := InitDB()
	if err != nil {
		log.Fatalf("初始化数据库失败: %v", err)
	}
	defer CloseDB()


	var wg sync.WaitGroup

	wg.Add(1)
	go func() {
		defer wg.Done()
		if *serverType == "tcp" {
			Logger.Printf("使用TCP服务器模式")
			if err := StartTCPServer(":" + *tcpPort); err != nil {
				log.Fatalf("TCP服务器启动失败: %v", err)
			}
		} else if *serverType == "udp" {
			Logger.Printf("使用UDP服务器模式")
			if err := StartUDPServer(":" + *udpPort); err != nil {
				log.Fatalf("UDP服务器启动失败: %v", err)
			}
		} else {
			log.Fatalf("未知的服务器类型: %s", *serverType)
		}
	}()

	wg.Add(1)
	go func() {
		defer wg.Done()
		if err := StartHTTPServer(":" + *httpPort); err != nil {
			log.Fatalf("HTTP服务器启动失败: %v", err)
		}
	}()

	if *serverType == "tcp" {
		fmt.Println("服务器已启动成功")
		fmt.Printf("- HTTP接口: http://localhost:%s\n", *httpPort)
		fmt.Printf("- TCP接口: localhost:%s\n", *tcpPort)
	} else {
		fmt.Println("服务器已启动成功")
		fmt.Printf("- HTTP接口: http://localhost:%s\n", *httpPort)
		fmt.Printf("- UDP接口: localhost:%s\n", *udpPort)
	}

	wg.Wait()
}
