package utils

import (
	"fmt"
	"os"
	"path/filepath"
	"sync"
	"time"
)

// DailyLogWriter 实现 io.Writer 接口，支持按天轮转日志
type DailyLogWriter struct {
	Dir     string
	file    *os.File
	curDate string
	mu      sync.Mutex
}

func NewDailyLogWriter(dir string) *DailyLogWriter {
	if err := os.MkdirAll(dir, 0755); err != nil {
		fmt.Printf("Failed to create log dir: %v\n", err)
	}
	return &DailyLogWriter{
		Dir: dir,
	}
}

func (w *DailyLogWriter) Write(p []byte) (n int, err error) {
	w.mu.Lock()
	defer w.mu.Unlock()

	today := time.Now().Format("2006-01-02")
	// 如果日期变更或文件未打开，则切换文件
	if w.curDate != today || w.file == nil {
		if w.file != nil {
			w.file.Close()
		}

		w.curDate = today
		fpath := filepath.Join(w.Dir, fmt.Sprintf("%s.log", today))
		
		// 以追加模式打开/创建文件
		f, err := os.OpenFile(fpath, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
		if err != nil {
			os.Stderr.Write([]byte(fmt.Sprintf("Failed to open log file: %v\n", err)))
			return os.Stderr.Write(p) // 降级输出到 stderr
		}
		w.file = f
	}

	return w.file.Write(p)
}
