// internal/provcommon/common.go
package provcommon

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

	"zlh-agent/internal/state"
)

const (
	// Root for all ZLH-managed game data inside the container.
	// New layout: /opt/zlh/<game>/<variant>/world
	ServersRoot  = "/opt/zlh"
	JavaRoot     = "/opt/zlh/runtime"
	SteamCMDPath = "/opt/zlh/steamcmd"
)

// ServerDir determines where a game's server files live.
//
// Final layout:
//   /opt/zlh/<game>/<variant>/world
//
// Examples:
//   minecraft + forge   -> /opt/zlh/minecraft/forge/world
//   minecraft + vanilla -> /opt/zlh/minecraft/vanilla/world
//   valheim + vanilla   -> /opt/zlh/valheim/vanilla/world
func ServerDir(cfg state.Config) string {
	game := strings.ToLower(cfg.Game)
	if game == "" {
		game = "unknown"
	}

	variant := strings.ToLower(cfg.Variant)
	if variant == "" {
		variant = "vanilla"
	}

	world := strings.ToLower(cfg.World)
	if world == "" {
		world = "world"
	}

	return filepath.Join(ServersRoot, game, variant, world)
}

// JavaDir returns the root of the extracted JDK runtime.
func JavaDir(cfg state.Config) string {
	return JavaRoot
}

// BuildArtifactURL resolves relative artifact paths into full URLs.
func BuildArtifactURL(path string) string {
	if strings.HasPrefix(path, "http://") || strings.HasPrefix(path, "https://") {
		return path
	}

	base := os.Getenv("ZLH_ARTIFACT_BASE_URL")
	if base == "" {
		base = "http://zlh-artifacts.internal.zlh:8080/"
	}

	return strings.TrimRight(base, "/") + "/" + strings.TrimLeft(path, "/")
}
