package backup

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

	"zlh-agent/internal/state"
)

var (
	backupLogMu   sync.Mutex
	backupLogPath = "/opt/zlh-agent/logs/backup_restore.log"
)

func backupLogf(cfg *state.Config, format string, args ...any) {
	line := fmt.Sprintf(format, args...)
	prefix := fmt.Sprintf("[%s]", time.Now().UTC().Format(time.RFC3339))
	if cfg != nil {
		prefix += fmt.Sprintf(" vmid=%d type=%s game=%s variant=%s version=%s",
			cfg.VMID,
			strings.TrimSpace(cfg.ContainerType),
			strings.TrimSpace(cfg.Game),
			strings.TrimSpace(cfg.Variant),
			strings.TrimSpace(cfg.Version),
		)
	}

	backupLogMu.Lock()
	defer backupLogMu.Unlock()

	if err := os.MkdirAll(filepath.Dir(backupLogPath), 0o755); err != nil {
		return
	}
	f, err := os.OpenFile(backupLogPath, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0o644)
	if err != nil {
		return
	}
	defer f.Close()
	_, _ = f.WriteString(prefix + " " + line + "\n")
}
