package main

import (
	"fmt"
	"log"
	"os"
	"path/filepath"
	"runtime/debug"
	"time"

	"git.lxtend.com/lixiangwuxian/qqbot/config"
	"git.lxtend.com/lixiangwuxian/qqbot/service/exec"
	"git.lxtend.com/lixiangwuxian/qqbot/sqlite3"
	"git.lxtend.com/lixiangwuxian/qqbot/webserver"
	_ "git.lxtend.com/lixiangwuxian/qqbot/works"
	wsclient "git.lxtend.com/lixiangwuxian/qqbot/ws_client"
	"github.com/gin-gonic/gin"
)

func init() {
	// 创建logs目录
	if err := os.MkdirAll("logs", 0755); err != nil {
		log.Printf("创建logs目录失败: %v", err)
	}

	// 设置日志输出到文件
	logFile, err := os.OpenFile(filepath.Join("logs", "log.txt"), os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0644)
	if err != nil {
		log.Printf("打开日志文件失败: %v", err)
		return
	}
	log.SetOutput(logFile)
}

func main() {
	var stopRun = false
	// 创建 WebSocket 客户端
	defer func() {
		if err := recover(); err != nil {
			// 获取详细的堆栈信息
			stack := debug.Stack()
			errMsg := fmt.Sprintf("[%s] Panic recovered:\nError: %v\nStack Trace:\n%s\n",
				time.Now().Format("2006-01-02 15:04:05"), err, stack)

			// 写入日志文件
			log.Print(errMsg)
		}
		stopRun = true
		main()
	}()
	defer exec.DockerContainer.RemoveContainer()
	defer sqlite3.CloseDB()
	gin.SetMode(gin.ReleaseMode)
	sqlite3.InitDB()
	go func() {
		const reconnectDelay = 5 * time.Second
		for !stopRun {
			client, err := wsclient.NewWebSocketClient("ws", config.ConfigManager.GetConfig().Management.NapcatWsSrv, "")
			if err != nil {
				log.Printf("WebSocket连接失败: %v, %v 后重试", err, reconnectDelay)
				time.Sleep(reconnectDelay)
				continue
			}

			// 等待连接关闭
			<-client.Done
			client.Close()

			log.Printf("WebSocket连接断开, %v 后重连", reconnectDelay)
			time.Sleep(reconnectDelay)
		}
	}()
	webserver.StartRouter()
	for {
		time.Sleep(1000 * time.Second)
	}
}
