// Copyright 2026 printing-press-golden and contributors. 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 (
	mcplib "github.com/mark3labs/mcp-go/mcp"
	"github.com/mark3labs/mcp-go/server"
	"github.com/spf13/cobra"
)

// RegisterAll walks root's user-facing Cobra commands and registers shell-out
// MCP tools for commands that are not already covered by typed endpoint tools.
func RegisterAll(s *server.MCPServer, root *cobra.Command, cliPath func() (string, error)) {
	if root == nil {
		return
	}
	walk(root, nil, func(cmd *cobra.Command, path []string) {
		switch classify(cmd) {
		case commandHidden:
			return
		case commandEndpoint, commandFramework:
			return
		}
		if !cmd.Runnable() {
			return
		}

		toolName := toolNameForPath(path)
		if toolName == "" {
			return
		}
		if s.GetTool(toolName) != nil {
			return
		}
		blockedStructuredArgs := blockedStructuredArgsForCommand(cmd)
		positionals := positionalArgsForCommand(cmd, blockedStructuredArgs)
		blockedCLIArgs := cliFlagBlockedArgs(blockedStructuredArgs, positionals)
		allowedStructuredArgs := allowedStructuredArgsForCommand(cmd, blockedStructuredArgs, positionals, commandTakesArgs(cmd))
		options := []mcplib.ToolOption{mcplib.WithDescription(descriptionFor(cmd))}
		options = append(options, toolOptionsForFlags(cmd, blockedStructuredArgs, positionals)...)
		if commandTakesArgs(cmd) && len(positionals) == 0 {
			options = append(options, mcplib.WithString("args", mcplib.Description("Additional positional arguments to append to the command. Raw flags are rejected; use structured flag parameters instead.")))
		}
		readOnly := isMCPReadOnly(cmd)
		if readOnly {
			options = append(options, mcplib.WithReadOnlyHintAnnotation(true), mcplib.WithDestructiveHintAnnotation(false))
		}
		s.AddTool(mcplib.NewTool(toolName, options...), shellOutToCLI(cliPath, path, blockedCLIArgs, allowedStructuredArgs, positionals, readOnly, positionalWriteSinkIndexes(cmd)))
	})
}

func walk(cmd *cobra.Command, path []string, visit func(*cobra.Command, []string)) {
	for _, child := range cmd.Commands() {
		if child.Hidden || isMCPHidden(child) {
			continue
		}
		childPath := append(append([]string{}, path...), child.Name())
		visit(child, childPath)
		if kind := classify(child); kind != commandHidden && kind != commandFramework {
			walk(child, childPath, visit)
		}
	}
}

func descriptionFor(cmd *cobra.Command) string {
	if cmd.Long != "" {
		return cmd.Long
	}
	if cmd.Short != "" {
		return cmd.Short
	}
	return "Run `" + cmd.CommandPath() + "` through the companion CLI binary."
}
