package util

import (
	"fmt"
	"io"
	"log"
	"os"
	"time"
)

var (
	logFile       *os.File
	lifecycleFile *os.File
	logReady      bool
)

// InitLogFile sets up a log file inside the agent directory.
// Called from main.go (optional).
func InitLogFile(path string) error {
	f, err := os.OpenFile(path, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0644)
	if err != nil {
		return err
	}
	logFile = f
	logReady = true
	log.SetOutput(io.MultiWriter(os.Stdout, logFile))
	return nil
}

func CloseLog() {
	if logReady && logFile != nil {
		_ = logFile.Close()
	}
	if lifecycleFile != nil {
		_ = lifecycleFile.Close()
	}
}

// Log writes a timestamped line to stdout AND to log file (if enabled).
func Log(format string, v ...any) {
	line := fmt.Sprintf("[%s] %s",
		time.Now().Format("2006-01-02 15:04:05"),
		fmt.Sprintf(format, v...),
	)

	// Always print to stdout
	log.Println(line)

	// Optionally also write to file
	if logReady && logFile != nil {
		_, _ = logFile.WriteString(line + "\n")
	}
}

func InitLifecycleLog(path string) error {
	f, err := os.OpenFile(path, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0644)
	if err != nil {
		return err
	}
	lifecycleFile = f
	return nil
}

func LogLifecycle(format string, v ...any) {
	line := fmt.Sprintf("[%s] %s",
		time.Now().Format("2006-01-02 15:04:05"),
		fmt.Sprintf(format, v...),
	)
	log.Println(line)
	if lifecycleFile != nil {
		_, _ = lifecycleFile.WriteString(line + "\n")
	}
}
