package cmd

import (
	"fmt"
	"strings"

	"nest/src/catalog"
	"nest/src/output"
)

const infoUsage = `Usage: nest info <tool> [--json] [--catalog path]

Show full details of one catalog entry, including the suggested run command.
Exits 3 if the tool is not in the catalog.
`

func (a *App) cmdInfo(args []string) int {
	fs := a.newFlagSet("info", infoUsage)
	jsonOut := fs.Bool("json", false, "JSON output (stable schema, see AGENTS.md §4.8)")
	catalogFlag := fs.String("catalog", "", "use the catalog at path (development/testing)")
	positionals, ok, code := a.parseInterspersed(fs, args)
	if !ok {
		return code
	}
	if len(positionals) != 1 {
		fmt.Fprintf(a.Stderr, "nest: info takes exactly one tool name\n")
		return exitUsage
	}

	cat, _, code := a.loadCatalog(*catalogFlag)
	if code != exitOK {
		return code
	}
	tool, found := cat.Find(positionals[0])
	if !found {
		fmt.Fprintf(a.Stderr, "nest: tool %q not found in catalog; try: nest search %s\n", positionals[0], positionals[0])
		return exitNotFound
	}

	info := output.Info(tool)
	if *jsonOut {
		if err := output.JSON(a.Stdout, info); err != nil {
			fmt.Fprintf(a.Stderr, "nest: cannot render JSON: %v\n", err)
			return exitError
		}
		return exitOK
	}
	a.printInfo(&info)
	return exitOK
}

func (a *App) printInfo(info *output.ToolInfo) {
	w := a.Stdout
	fmt.Fprintf(w, "Name:        %s\n", info.Name)
	fmt.Fprintf(w, "Description: %s\n", info.Description)
	fmt.Fprintf(w, "Package:     %s\n", info.Package)
	fmt.Fprintf(w, "Status:      %s\n", statusWord(info.Installed))

	execs := make([]string, 0, len(info.Executables))
	for _, e := range info.Executables {
		word := "missing"
		if e.Present {
			word = "present"
		}
		execs = append(execs, e.Path+" ("+word+")")
	}
	fmt.Fprintf(w, "Executables: %s\n", strings.Join(execs, ", "))

	images := "(none)"
	if len(info.Images) > 0 {
		list := make([]string, 0, len(info.Images))
		for i, img := range info.Images {
			if i == 0 {
				img += " (default)"
			}
			list = append(list, img)
		}
		images = strings.Join(list, ", ")
	}
	fmt.Fprintf(w, "Images:      %s\n", images)

	if info.Container != nil {
		fmt.Fprintf(w, "Container:   %s\n", containerSummary(info.Container))
	}
	fmt.Fprintf(w, "Tags:        %s\n", strings.Join(info.Tags, ", "))
	fmt.Fprintf(w, "Run:         %s\n", info.SuggestedRun)
}

func containerSummary(c *catalog.Container) string {
	var parts []string
	if c.Network != "" {
		parts = append(parts, "network="+c.Network)
	}
	if len(c.CapAdd) > 0 {
		parts = append(parts, "cap_add="+strings.Join(c.CapAdd, ","))
	}
	if len(c.ExtraArgs) > 0 {
		parts = append(parts, "extra_args="+strings.Join(c.ExtraArgs, " "))
	}
	return strings.Join(parts, ", ")
}
