package lookpath

import (
	"context"
	"flag"
	"fmt"

	"gitlab.com/gitlab-org/fleeting/fleeting-artifact/pkg/installer"
)

type lookpathCmd struct {
	fs *flag.FlagSet
}

func New() *lookpathCmd {
	c := &lookpathCmd{}
	c.fs = flag.NewFlagSet("lookpath", flag.ExitOnError)
	c.fs.Usage = func() {
		fmt.Fprintln(c.fs.Output(), c.fs.Name(), "NAME[:VERSION_CONSTRAINT]")
		fmt.Fprintf(c.fs.Output(), "\n  Returns the path for a locally installed plugin matching the version constraint provided.\n")
		c.fs.PrintDefaults()
	}

	return c
}

func (cmd *lookpathCmd) Command() *flag.FlagSet {
	return cmd.fs
}

func (cmd *lookpathCmd) Execute(ctx context.Context) error {
	if len(cmd.fs.Args()) < 1 {
		return flag.ErrHelp
	}

	path, err := installer.LookPath(cmd.fs.Arg(0), "")
	if err != nil {
		return err
	}

	fmt.Println(path)

	return nil
}
