package cli

import (
	"fmt"
	"os"
	"strings"
)

func workspaceDir(w string) string {
	return strings.TrimSpace(w)
}

func prepareWorkspaceDir(w string) (string, error) {
	dir := workspaceDir(w)
	if dir == "" {
		return "", nil
	}
	info, err := os.Stat(dir)
	if err != nil {
		if os.IsNotExist(err) {
			return "", fmt.Errorf("cli adapter: workspace not found: %s", dir)
		}
		return "", fmt.Errorf("cli adapter: workspace inaccessible: %s: %w", dir, err)
	}
	if !info.IsDir() {
		return "", fmt.Errorf("cli adapter: workspace is not a directory: %s", dir)
	}
	if f, err := os.Open(dir); err != nil {
		return "", fmt.Errorf("cli adapter: workspace inaccessible: %s: %w", dir, err)
	} else {
		_ = f.Close()
	}
	return dir, nil
}
