package parser

import (
	"regexp"
	"strings"
	"time"
)

type LogEvent struct {
	Timestamp      time.Time `json:"timestamp"`
	Type           string    `json:"type"` // 'CHAT', 'JOIN', 'LEAVE', 'ADMIN', 'GENERIC'
	Content        string    `json:"content"`
	PlayerName     string    `json:"playerName,omitempty"`
	PlayerNameHash string    `json:"playerNameHash,omitempty"`
	ServerID       string    `json:"serverId,omitempty"`
	ServerName     string    `json:"serverName,omitempty"`
	Raw            string    `json:"raw,omitempty"`
}

// Reforger-specific regex patterns
var (
	// Example: 12:30:01.122   SCRIPT       : [RJSSupport][Chat] [Global] Zauberklöte: hi, leute...
	chatRegex = regexp.MustCompile(`^(\d{2}:\d{2}:\d{2}\.\d{3})\s+SCRIPT\s+:\s+\[.*?\]\[Chat\]\s+\[.*?\]\s+(.*?):\s+(.*)$`)
	// Example: 09:37:50.865  DEFAULT      : BattlEye Server: 'Player #0 Mike1Delta (92.209.175.19:6679) connected'
	joinRegex = regexp.MustCompile(`^(\d{2}:\d{2}:\d{2}\.\d{3})\s+DEFAULT\s+:\s+BattlEye Server:\s+'Player #\d+\s+(.*?)\s+\(.*?\) connected'$`)
	// Example: 09:38:53.842  DEFAULT      : BattlEye Server: 'Player #0 Mike1Delta disconnected'
	leaveRegex = regexp.MustCompile(`^(\d{2}:\d{2}:\d{2}\.\d{3})\s+DEFAULT\s+:\s+BattlEye Server:\s+'Player #\d+\s+(.*?) disconnected'$`)
)

func ParseLine(line string) *LogEvent {
	line = strings.TrimSpace(line)
	if line == "" {
		return nil
	}

	event := &LogEvent{
		Raw:  line,
		Type: "GENERIC",
	}

	// Try Chat
	if matches := chatRegex.FindStringSubmatch(line); matches != nil {
		event.Type = "CHAT"
		event.PlayerName = matches[2]
		event.Content = matches[2] + ": " + matches[3]
		return event
	}

	// Try Join
	if matches := joinRegex.FindStringSubmatch(line); matches != nil {
		event.Type = "JOIN"
		event.PlayerName = matches[2]
		event.Content = matches[2] + " connected to server"
		return event
	}

	// Try Leave
	if matches := leaveRegex.FindStringSubmatch(line); matches != nil {
		event.Type = "LEAVE"
		event.PlayerName = matches[2]
		event.Content = matches[2] + " left the server"
		return event
	}

	return event
}
