package cmd

import (
	"fmt"

	"nest/src/detect"
	"nest/src/output"
	"nest/src/runtime"
)

const versionUsage = `Usage: nest version [--json] [--catalog path]

Show nest version, catalog version and source, detected runtime, and
container-mode status.
`

func (a *App) cmdVersion(args []string) int {
	fs := a.newFlagSet("version", versionUsage)
	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)")
	if ok, code := a.parseFlags(fs, args); !ok {
		return code
	}

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

	v := output.Version{
		Nest:           a.Version,
		CatalogVersion: cat.Version,
		CatalogSource:  source,
		ContainerMode:  detect.InContainer(a.Getenv),
	}
	if rt, err := runtime.Auto(); err == nil {
		name := rt.Name()
		v.Runtime = &name
	}

	if *jsonOut {
		if err := output.JSON(a.Stdout, v); err != nil {
			fmt.Fprintf(a.Stderr, "nest: cannot render JSON: %v\n", err)
			return exitError
		}
		return exitOK
	}
	rtName := "none"
	if v.Runtime != nil {
		rtName = *v.Runtime
	}
	fmt.Fprintf(a.Stdout, "nest version:    %s\n", v.Nest)
	fmt.Fprintf(a.Stdout, "catalog version: %d (%s)\n", v.CatalogVersion, v.CatalogSource)
	fmt.Fprintf(a.Stdout, "runtime:         %s\n", rtName)
	fmt.Fprintf(a.Stdout, "container mode:  %t\n", v.ContainerMode)
	return exitOK
}
