package logger

import (
	"fmt"
	"sync"
	"time"
)

// LogEntry 日志条目
type LogEntry struct {
	Timestamp time.Time `json:"timestamp"`
	Level     string    `json:"level"`
	Message   string    `json:"message"`
	Email     string    `json:"email,omitempty"`
	Module    string    `json:"module,omitempty"`
}

// 日志存储
var (
	logs      = make([]LogEntry, 0, 1000)
	logsMu    sync.RWMutex
	listeners = make(map[string]chan LogEntry)
	listMu    sync.RWMutex
)

// AddListener 添加日志监听器
func AddListener(id string) chan LogEntry {
	listMu.Lock()
	defer listMu.Unlock()
	ch := make(chan LogEntry, 100)
	listeners[id] = ch
	return ch
}

// RemoveListener 移除日志监听器
func RemoveListener(id string) {
	listMu.Lock()
	defer listMu.Unlock()
	if ch, ok := listeners[id]; ok {
		close(ch)
		delete(listeners, id)
	}
}

// broadcast 广播日志
func broadcast(entry LogEntry) {
	listMu.RLock()
	defer listMu.RUnlock()
	for _, ch := range listeners {
		select {
		case ch <- entry:
		default:
		}
	}
}

// log 记录日志
func log(level, message, email, module string) {
	entry := LogEntry{
		Timestamp: time.Now(),
		Level:     level,
		Message:   message,
		Email:     email,
		Module:    module,
	}

	logsMu.Lock()
	if len(logs) >= 1000 {
		logs = logs[100:]
	}
	logs = append(logs, entry)
	logsMu.Unlock()

	broadcast(entry)

	// 打印到控制台
	prefix := ""
	switch level {
	case "info":
		prefix = "[INFO]"
	case "success":
		prefix = "[SUCCESS]"
	case "error":
		prefix = "[ERROR]"
	case "warning":
		prefix = "[WARN]"
	}

	if email != "" {
		fmt.Printf("%s [%s] %s - %s\n", prefix, module, email, message)
	} else {
		fmt.Printf("%s [%s] %s\n", prefix, module, message)
	}
}

// Info 记录信息日志
func Info(message, email, module string) {
	log("info", message, email, module)
}

// Success 记录成功日志
func Success(message, email, module string) {
	log("success", message, email, module)
}

// Error 记录错误日志
func Error(message, email, module string) {
	log("error", message, email, module)
}

// Warning 记录警告日志
func Warning(message, email, module string) {
	log("warning", message, email, module)
}

// GetLogs 获取日志
func GetLogs(limit int) []LogEntry {
	logsMu.RLock()
	defer logsMu.RUnlock()

	if limit <= 0 || limit > len(logs) {
		limit = len(logs)
	}

	start := len(logs) - limit
	if start < 0 {
		start = 0
	}

	result := make([]LogEntry, limit)
	copy(result, logs[start:])
	return result
}

// ClearLogs 清空日志
func ClearLogs() {
	logsMu.Lock()
	defer logsMu.Unlock()
	logs = make([]LogEntry, 0, 1000)
}
