package cli

import (
	"fmt"
	"path"
	"strings"

	"github.com/spf13/pflag"
)

var _ pflag.Value = (*pathPrefixValue)(nil)

type pathPrefixValue struct {
	p    *string
	name string
}

func registerPathPrefixFlag(flags *pflag.FlagSet, p *string, name string, val string, usage string) {
	*p = val
	flags.Var(&pathPrefixValue{p, name}, name, usage)
}

func (v *pathPrefixValue) Type() string   { return "string" }
func (v *pathPrefixValue) String() string { return *v.p }

func (v *pathPrefixValue) Set(raw string) error {
	trimmed := strings.Trim(raw, "/")
	if trimmed == "" {
		*v.p = ""
		return nil
	}

	cleaned := path.Clean(trimmed)
	if cleaned == "." {
		*v.p = ""
		return nil
	}
	if cleaned == ".." || strings.HasPrefix(cleaned, "../") {
		return usageError{fmt.Sprintf("%s %q escapes", v.name, raw)}
	}

	*v.p = cleaned
	return nil
}

func prefixedPath(prefix string, filePath string) string {
	if prefix == "" {
		return filePath
	}
	return path.Join(prefix, filePath)
}
