package logger

import (
	"fmt"
	"io"
	"log"
	"os"
	"path/filepath"
	"time"
)

var (
	logFile *os.File
	Logger  *log.Logger
)

// 初始化日志系统
func InitLogger() error {
	logsDir := "logs"
	if err := os.MkdirAll(logsDir, 0755); err != nil {
		return fmt.Errorf("创建日志目录失败: %v", err)
	}

	today := time.Now().Format("2006-01-02")
	logFilePath := filepath.Join(logsDir, fmt.Sprintf("server_%s.log", today))

	file, err := os.OpenFile(logFilePath, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
	if err != nil {
		return fmt.Errorf("打开日志文件失败: %v", err)
	}

	logFile = file
	multiWriter := io.MultiWriter(os.Stdout, file)
	Logger = log.New(multiWriter, "", log.Ldate|log.Ltime|log.Lshortfile)

	log.SetOutput(multiWriter)
	log.SetFlags(log.Ldate | log.Ltime | log.Lshortfile)

	Logger.Println("日志系统初始化完成")
	return nil
}

// 关闭日志文件
func CloseLogger() {
	if logFile != nil {
		logFile.Close()
	}
}

// 日志轮转，每天创建新的日志文件
func StartLogRotation() {
	go func() {
		for {
			now := time.Now()
			next := now.Add(24 * time.Hour)
			next = time.Date(next.Year(), next.Month(), next.Day(), 0, 0, 0, 0, next.Location())
			duration := next.Sub(now)

			time.Sleep(duration)

			Logger.Println("开始日志轮转...")
			CloseLogger()
			if err := InitLogger(); err != nil {
				log.Printf("日志轮转失败: %v", err)
			}
		}
	}()
}
