package topdata

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

	"gitea.westgate.pw/ShadowsOverWestgate/sow-tools/internal/project"
)

func resolvePartsAssetsOverrideDir(p *project.Project) (string, error) {
	spec := strings.TrimSpace(p.Config.TopData.Assets)
	if spec == "" {
		return "", nil
	}
	if looksLikeGitRepoSpec(spec) {
		return "", fmt.Errorf("topdata.assets no longer supports git repo specs for parts discovery; use a local path override or the default released manifest")
	}
	path := p.TopDataAssetsDir()
	if path == "" {
		return "", nil
	}
	if _, err := os.Stat(path); err != nil {
		return "", fmt.Errorf("configured topdata.assets path %s is not accessible: %w", path, err)
	}
	return path, nil
}

func looksLikeGitRepoSpec(value string) bool {
	return strings.Contains(value, "://") ||
		strings.HasPrefix(value, "git@") ||
		strings.HasSuffix(value, ".git")
}

func gitOutput(dir string, args ...string) (string, error) {
	cmd := exec.Command("git", args...)
	if dir != "" {
		cmd.Dir = dir
	}
	output, err := cmd.CombinedOutput()
	if err != nil {
		return "", fmt.Errorf("%v: %s", args, strings.TrimSpace(string(output)))
	}
	return strings.TrimSpace(string(output)), nil
}
