package server

import (
	"context"
	"fmt"
	"go.uber.org/zap/zapcore"
	"log"
	"net/http"
	"os"
	"os/signal"

	_ "skapp/pkg/server/docs"

	"skapp/global"
	"skapp/pkg/config/toml"
	"skapp/pkg/logger"
	"time"
)

// @title Wails AssetServer API
// @version 1.0
// @description Wails AssetServer API 文档
// @termsOfService http://swagger.io/terms/
// @contact.name Shikong
// @contact.email 919411476@qq.com
// @license.name Apache 2.0
// @license.url http://www.apache.org/licenses/LICENSE-2.0.html
// @BasePath /s

func Main() {
	conf, err := toml.LoadConfig()
	if err != nil {
		logger.Log.Fatalf("%s", err)
	}

	global.Config = conf

	if conf.HasDebug() && conf.Debug.Enable {
		logger.SetLevel(zapcore.DebugLevel)
	} else {
		logger.SetLevel(zapcore.ErrorLevel)
	}

	engine := Server(conf)

	srv := &http.Server{
		Addr:    fmt.Sprintf("%s:%d", conf.Server.Host, conf.Server.Port),
		Handler: engine,
	}

	go func() {
		logger.Log.Infof("服务启动 %s", fmt.Sprintf("%s:%d", conf.Server.Host, conf.Server.Port))
		if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
			logger.Log.Fatalf("listen: %s\n", err)
		}
	}()

	// 等待中断信号以优雅地关闭服务器（设置 5 秒的超时时间）
	quit := make(chan os.Signal, 1)
	signal.Notify(quit, os.Interrupt)
	<-quit
	logger.Log.Info("开始关闭服务")

	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()
	if err := srv.Shutdown(ctx); err != nil {
		log.Fatal("服务关闭异常:", err)
	}
	logger.Log.Info("服务关闭完成")
}
