package steam

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

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

func GameDir(cfg state.Config) string {
	return provcommon.ServerDir(cfg)
}

func EnsureSteamCMD() error {
	path := filepath.Join(provcommon.SteamCMDPath, "steamcmd.sh")
	if _, err := os.Stat(path); err != nil {
		return fmt.Errorf("steamcmd not found at %s", path)
	}
	return nil
}

func RunSteamCMD(args ...string) error {
	if err := EnsureSteamCMD(); err != nil {
		return err
	}

	steamcmd := filepath.Join(provcommon.SteamCMDPath, "steamcmd.sh")

	flatArgs := []string{}
	for _, a := range args {
		parts := strings.Fields(a)
		flatArgs = append(flatArgs, parts...)
	}

	cmd := exec.Command(steamcmd, flatArgs...)
	cmd.Stdout = os.Stdout
	cmd.Stderr = os.Stderr

	return cmd.Run()
}

func EnsureGameDir(cfg state.Config) (string, error) {
	dir := GameDir(cfg)
	if err := os.MkdirAll(dir, 0o755); err != nil {
		return "", fmt.Errorf("mkdir game dir: %w", err)
	}
	return dir, nil
}

func ValidateApp(appID string) error {
	if strings.TrimSpace(appID) == "" {
		return fmt.Errorf("invalid Steam App ID")
	}
	return nil
}

func SteamLoginArgs(cfg state.Config) string {
	user := strings.TrimSpace(cfg.SteamUser)
	pass := strings.TrimSpace(cfg.SteamPass)
	auth := strings.TrimSpace(cfg.SteamAuth)

	// Default: anonymous login if nothing set
	if user == "" {
		return "anonymous"
	}

	parts := []string{user}
	if pass != "" {
		parts = append(parts, pass)
	}
	if auth != "" {
		parts = append(parts, auth)
	}

	return strings.Join(parts, " ")
}
