package utils

import (
	"bufio"
	"io"
	"log"
	"os"
	"path/filepath"
)

var logFilePath = "data/app.log"

func InitLogger() {
	logDir := filepath.Dir(logFilePath)
	if logDir != "." && logDir != "/" {
		if err := os.MkdirAll(logDir, 0755); err != nil {
			log.Fatalf("Failed to create log directory %s: %v", logDir, err)
		}
	}

	file, err := os.OpenFile(logFilePath, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0644)
	if err != nil {
		log.Fatalf("Failed to open log file %s: %v", logFilePath, err)
	}

	multiWriter := io.MultiWriter(os.Stdout, file)
	log.SetOutput(multiWriter)

	log.Printf("Logger initialized, log file: %s", logFilePath)
}

func GetLogs(lines int) ([]string, error) {
	file, err := os.Open(logFilePath)
	if err != nil {
		return nil, err
	}
	defer file.Close()

	ring := make([]string, 0, lines)
	idx := 0

	scanner := bufio.NewScanner(file)
	buf := make([]byte, 0, 64*1024)
	scanner.Buffer(buf, 1024*1024)

	for scanner.Scan() {
		line := scanner.Text()
		if len(ring) < cap(ring) {
			ring = append(ring, line)
		} else {
			ring[idx] = line
		}
		idx = (idx + 1) % cap(ring)
	}

	if err := scanner.Err(); err != nil {
		return nil, err
	}

	if len(ring) < cap(ring) {
		return ring, nil
	}

	result := make([]string, len(ring))
	for i := 0; i < len(ring); i++ {
		result[i] = ring[(idx+i)%len(ring)]
	}
	return result, nil
}

func ClearLogs() error {
	file, err := os.OpenFile(logFilePath, os.O_WRONLY|os.O_TRUNC, 0644)
	if err != nil {
		return err
	}
	defer file.Close()
	return nil
}

func GetLogSize() (int64, error) {
	info, err := os.Stat(logFilePath)
	if err != nil {
		return 0, err
	}
	return info.Size(), nil
}

func GetLogModTime() (interface{}, error) {
	info, err := os.Stat(logFilePath)
	if err != nil {
		return nil, err
	}
	return info.ModTime(), nil
}
