// Copyright 2026 printing-press-golden. Licensed under Apache-2.0. See LICENSE.
// Generated by CLI Printing Press (https://github.com/mvanhorn/cli-printing-press). DO NOT EDIT.

package cobratree

import (
	"regexp"
	"strings"

	mcplib "github.com/mark3labs/mcp-go/mcp"
	"github.com/spf13/cobra"
	"github.com/spf13/pflag"
)

var positionalPattern = regexp.MustCompile(`(?:^|\s)(?:<[^>]+>|\[[^\]]+\])`)

func toolOptionsForFlags(cmd *cobra.Command) []mcplib.ToolOption {
	var opts []mcplib.ToolOption
	seen := map[string]bool{}
	addFlag := func(flag *pflag.Flag) {
		if flag == nil || flag.Hidden || flag.Deprecated != "" {
			return
		}
		if seen[flag.Name] {
			return
		}
		seen[flag.Name] = true
		opts = append(opts, toolOptionForFlag(flag))
	}
	cmd.InheritedFlags().VisitAll(addFlag)
	cmd.NonInheritedFlags().VisitAll(addFlag)
	return opts
}

func toolOptionForFlag(flag *pflag.Flag) mcplib.ToolOption {
	propOpts := []mcplib.PropertyOption{mcplib.Description(flagDescription(flag))}
	if isRequired(flag) {
		propOpts = append(propOpts, mcplib.Required())
	}
	switch flag.Value.Type() {
	case "bool":
		return mcplib.WithBoolean(flag.Name, propOpts...)
	case "int", "int8", "int16", "int32", "int64",
		"uint", "uint8", "uint16", "uint32", "uint64",
		"float32", "float64", "count":
		return mcplib.WithNumber(flag.Name, propOpts...)
	case "string", "stringSlice", "stringArray", "duration":
		return mcplib.WithString(flag.Name, propOpts...)
	default:
		propOpts[0] = mcplib.Description(flagDescription(flag) + " (unknown Cobra flag type " + flag.Value.Type() + "; pass as a string)")
		return mcplib.WithString(flag.Name, propOpts...)
	}
}

func flagDescription(flag *pflag.Flag) string {
	usage := strings.TrimSpace(flag.Usage)
	if usage == "" {
		usage = "Value for --" + flag.Name
	}
	if flag.DefValue != "" && flag.DefValue != "[]" {
		usage += " (default: " + flag.DefValue + ")"
	}
	return usage
}

func isRequired(flag *pflag.Flag) bool {
	if flag == nil || flag.Annotations == nil {
		return false
	}
	_, ok := flag.Annotations[cobra.BashCompOneRequiredFlag]
	return ok
}

func commandTakesArgs(cmd *cobra.Command) bool {
	return positionalPattern.MatchString(cmd.Use)
}
