package opt

/*
Example use:

```go
package main

import (
	"fmt"
	"log"

	"git.sr.ht/~rjarry/go-opt/v2"
)

type Foo struct {
	Delay time.Duration `opt:"-t" action:"ParseDelay" default:"1s"`
	Force bool          `opt:"-f"`
	Name  string        `opt:"name" required:"false" metavar:"FOO"`
	Cmd   []string      `opt:"..."`
}

func (f *Foo) ParseDelay(arg string) error {
	d, err := time.ParseDuration(arg)
	if err != nil {
		return err
	}
	f.Delay = d
	return nil
}

func main() {
	var foo Foo
	err := opt.CmdlineToStruct("foo -f bar baz 'xy z' ", &foo)
	if err != nil {
		log.Fatalf("error: %s\n", err)
	}
	fmt.Printf("%#v\n", foo)
}
```

```console
$ foo -f bar baz 'xy z'
Foo{Delay: 1000000000, Force: true, Name: "bar", Cmd: []string{"baz", "xy z"}}
$ foo -t
error: -t takes a value. Usage: foo [-t <delay>] [-f] [<name>] <cmd>...
```

## Supported tags

There is a set of tags that can be set on struct fields:

### `opt:"-f"`

Registers that this field is associated to the specified flag. Unless a custom
`action` method is specified, the flag value will be automatically converted
from string to the field type (only basic scalar types are supported: all
integers (both signed and unsigned), all floats and strings. If the field type
is `bool`, the flag will take no value. Only supports short flags for now.

### `opt:"blah"`

Field is associated to a positional argument.

### `opt:"..."`

Field will be mapped to all remaining arguments. If the field is `string`, the
raw command line will be stored preserving any shell quoting, otherwise the
field needs to be `[]string` and will receive the remaining arguments after
interpreting shell quotes.

### `opt:"-"`

Special value to indicate that this command will accept any argument without
any check nor parsing. The field on which it is set will not be updated and
should be called `Unused struct{}` as a convention. The field name must start
with an upper case to avoid linter warnings because of unused fields.

### `action:"ParseFoo"`

Custom method to be used instead of the default automatic conversion. Needs to
be a method with a pointer receiver to the struct itself, takes a single
`string` argument and may return an `error` to abort parsing. The `action`
method is responsible of updating the struct.

### `description:"foobaz"` or `desc:"foobaz"`

A description that is returned alongside arguments during autocompletion.

### `default:"foobaz"`

Default `string` value if not specified by the user. Will be processed by the
same conversion/parsing as any other argument.

### `metavar:"foo|bar|baz"`

Displayed name for argument values in the generated usage help.

### `required:"true|false"`

By default, flag arguments are optional and positional arguments are required.
Using this tag allows changing that default behaviour. If an argument is not
required, it will be surrounded by square brackets in the generated usage help.

### `aliases:"cmd1,cmd2"`

By default, arguments are interpreted for all command aliases. If this is
specified, this field/option will only be applicable to the specified command
aliases.

### `complete:"CompleteFoo"`

Custom method to return the valid completions for the annotated option
/ argument. Needs to be a method with a pointer receiver to the struct itself,
takes a single `string` argument and must return a `[]string` slice containing
the valid completions.

## Caveats

Depending on field types, the argument string values are parsed using the
appropriate conversion function.

If no `opt` tag is set on a field, it will be excluded from automated argument
parsing. It can still be updated indirectly via a custom `action` method.

Short flags can be combined like with `getopt(3)`:

* Flags with no value: `-abc` is equivalent to `-a -b -c`
* Flags with a value (options): `-j9` is equivalent to `-j 9`
*/

import (
	"errors"
	"fmt"
)

func CmdlineToStruct(cmdline string, v any) error {
	args := LexArgs(cmdline)
	return ArgsToStruct(args, v)
}

func ArgsToStruct(args *Args, v any) error {
	if args.Count() == 0 {
		return errors.New("empty command")
	}

	cmd := NewCmdSpec(args.Arg(0), v)
	if err := cmd.ParseArgs(args); err != nil {
		return fmt.Errorf("%w. Usage: %s", err, cmd.Usage())
	}

	return nil
}

func GetCompletions(cmdline string, v any) (completions []Completion, prefix string) {
	args := LexArgs(cmdline)
	if args.Count() == 0 {
		return nil, ""
	}
	spec := NewCmdSpec(args.Arg(0), v)
	return spec.GetCompletions(args)
}
