package main

import (
	"context"
	"gitee.ltd/lxh/wechat-robot/internal/minio"
	"gitee.ltd/lxh/wechat-robot/internal/tasks"
	"github.com/gofiber/fiber/v2/log"
	"os"
	"os/signal"
	"syscall"
	"time"

	"gitee.ltd/lxh/wechat-robot/internal/config"
	"gitee.ltd/lxh/wechat-robot/internal/docker"
	"gitee.ltd/lxh/wechat-robot/internal/model"
	"gitee.ltd/lxh/wechat-robot/internal/server"
)

func main() {
	// 加载配置
	cfg, err := config.Load()
	if err != nil {
		log.Fatalf("无法加载配置: %v", err)
	}

	if err = cfg.Validate(); err != nil {
		log.Fatalf("配置无效: %v", err)
	}

	// 初始化Minio
	minio.Init()

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

	// 初始化Docker客户端
	err = docker.InitClient(&cfg.Docker)
	if err != nil {
		log.Errorf("初始化Docker客户端失败: %v", err)
	}
	defer docker.CloseClient()

	// 启动容器监控
	db := model.GetDB()
	monitor := docker.NewContainerMonitor(db, time.Minute)
	ctx, cancel := context.WithCancel(context.Background())
	monitor.Start(ctx)

	// 创建HTTP服务器
	srv := server.New(cfg)

	// 设置路由
	srv.SetupRoutes()

	// 启动HTTP服务器
	go func() {
		if err = srv.Start(); err != nil {
			log.Errorf("Server error: %v", err)
		}
	}()

	log.Debug("Server started successfully")

	// 启动定时任务
	tasks.Start()

	// 优雅关闭
	quit := make(chan os.Signal, 1)
	signal.Notify(quit, os.Interrupt, syscall.SIGTERM)
	<-quit

	log.Warn("Shutting down...")
	cancel() // 停止容器监控

	// 关闭HTTP服务器
	if err = srv.Shutdown(); err != nil {
		log.Fatalf("Server shutdown failed: %v", err)
	}

	log.Warn("Server exited properly")
}
