package main

import (
	"context"
	"log"
	"os"
	"os/signal"
	"syscall"
	"time"

	"github.com/qy/hw-ws-service/internal/config"
	"github.com/qy/hw-ws-service/internal/rtcclient"
	"github.com/qy/hw-ws-service/internal/server"
)

func main() {
	log.SetFlags(log.LstdFlags | log.Lmsgprefix)
	log.SetPrefix("[hw-ws] ")

	cfg := config.Load()
	addr := cfg.WSHost + ":" + cfg.WSPort

	client := rtcclient.New(cfg.RTCBackendURL)
	srv := server.New(addr, client)

	// 后台启动服务器
	serverErr := make(chan error, 1)
	go func() {
		serverErr <- srv.ListenAndServe()
	}()

	// 监听系统信号（K8s 滚动更新发送 SIGTERM）
	sigCh := make(chan os.Signal, 1)
	signal.Notify(sigCh, syscall.SIGTERM, syscall.SIGINT)

	select {
	case err := <-serverErr:
		log.Fatalf("server error: %v", err)
	case sig := <-sigCh:
		log.Printf("received signal: %v, starting graceful shutdown...", sig)
	}

	// 优雅关闭：最长 80s（与 K8s terminationGracePeriodSeconds=90 配合）
	ctx, cancel := context.WithTimeout(context.Background(), 80*time.Second)
	defer cancel()
	srv.Shutdown(ctx)

	log.Println("shutdown complete")
}
