package minecraft

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

	"zlh-agent/internal/state"
)

/*
   EnforceForgeServerProperties
   - Runs AFTER first Forge/NeoForge server start
   - Ensures Velocity-compatible settings
   - Requires restart to take effect
*/
func EnforceForgeServerProperties(cfg state.Config) error {
	variant := strings.ToLower(cfg.Variant)
	if variant != "forge" && variant != "neoforge" {
		return nil
	}

	// Forge working directory is authoritative
	serverDir := filepath.Join("/opt/zlh/minecraft", variant, "world")
	propsPath := filepath.Join(serverDir, "server.properties")

	data, err := os.ReadFile(propsPath)
	if err != nil {
		return fmt.Errorf("read server.properties: %w", err)
	}

	lines := strings.Split(string(data), "\n")
	found := false

	for i, l := range lines {
		if strings.HasPrefix(l, "online-mode=") {
			lines[i] = "online-mode=false"
			found = true
		}
	}

	if !found {
		lines = append(lines, "online-mode=false")
	}

	out := strings.Join(lines, "\n")
	if err := os.WriteFile(propsPath, []byte(out), 0644); err != nil {
		return fmt.Errorf("write server.properties: %w", err)
	}

	return nil
}
