package minecraft

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

	"zlh-agent/internal/provcommon"
	"zlh-agent/internal/state"
)

/* --------------------------------------------------------------------------
   InstallMinecraftNeoForge
   - Uses cfg.ArtifactPath as the NeoForge installer path
   - Installs into /opt/zlh/minecraft/neoforge/world
----------------------------------------------------------------------------*/
func InstallMinecraftNeoForge(cfg state.Config) error {
	dir := provcommon.ServerDir(cfg)
	if err := os.MkdirAll(dir, 0o755); err != nil {
		return fmt.Errorf("mkdir server dir: %w", err)
	}

	if cfg.ArtifactPath == "" {
		return fmt.Errorf("artifact_path missing for neoforge install")
	}

	url := provcommon.BuildArtifactURL(cfg.ArtifactPath)

	installerPath := filepath.Join(dir, "neoforge-installer.jar")

	// Download NeoForge installer into server dir
	cmdDl := exec.Command("bash", "-c",
		fmt.Sprintf("cd %s && curl -fLo %s %q", dir, "neoforge-installer.jar", url),
	)
	cmdDl.Stdout = os.Stdout
	cmdDl.Stderr = os.Stderr

	fmt.Println("[neoforge] downloading installer from:", url)
	if err := cmdDl.Run(); err != nil {
		return fmt.Errorf("neoforge installer download failed: %w", err)
	}

	javaBin := filepath.Join(provcommon.JavaRoot, "java")

	// Run NeoForge installer
	cmd := exec.Command("/bin/bash", "-c",
		fmt.Sprintf("cd %s && %s -jar %s --installServer", dir, javaBin, installerPath),
	)

	cmd.Env = append(os.Environ(),
		"PATH=/opt/zlh/runtime:/opt/zlh/runtime/java:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
	)

	cmd.Stdout = os.Stdout
	cmd.Stderr = os.Stderr

	fmt.Println("[neoforge] running installer in", dir)
	if err := cmd.Run(); err != nil {
		return fmt.Errorf("neoforge installer failed: %w", err)
	}

	// Reuse same script patcher as Forge
	if err := patchForgeJavaCalls(dir); err != nil {
		return fmt.Errorf("patch java calls: %w", err)
	}

	return nil
}
