package cmd

import (
	"fmt"

	"nest/src/output"
)

const searchUsage = `Usage: nest search <term> [--json] [--catalog path]

Case-insensitive substring search over name, description, package, and tags,
always over the full catalog. No matches is not an error.
`

func (a *App) cmdSearch(args []string) int {
	fs := a.newFlagSet("search", searchUsage)
	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: search takes exactly one term\n")
		return exitUsage
	}

	cat, _, code := a.loadCatalog(*catalogFlag)
	if code != exitOK {
		return code
	}

	matches := cat.Search(positionals[0])
	summaries := make([]output.ToolSummary, 0, len(matches))
	var rows [][]string
	for _, t := range matches {
		s := output.Summarize(t)
		summaries = append(summaries, s)
		rows = append(rows, []string{s.Name, statusWord(s.Installed), containerWord(t.HasImage()), s.Package, s.Description})
	}

	if *jsonOut {
		if err := output.JSON(a.Stdout, summaries); err != nil {
			fmt.Fprintf(a.Stderr, "nest: cannot render JSON: %v\n", err)
			return exitError
		}
		return exitOK
	}
	if err := output.Table(a.Stdout, []string{"NAME", "STATUS", "CONTAINER", "PACKAGE", "DESCRIPTION"}, rows); err != nil {
		fmt.Fprintf(a.Stderr, "nest: cannot render table: %v\n", err)
		return exitError
	}
	return exitOK
}
