package edgecmd

import (
	"fmt"
	"sort"
	"strings"

	"github.com/spf13/cobra"

	"iop/packages/go/config"
)

func nodesCmd() *cobra.Command {
	c := &cobra.Command{
		Use:   "nodes",
		Short: "Inspect registered edge nodes",
		Long:  `Inspect and list configured or connected execution nodes.`,
	}
	c.AddCommand(nodesListCmd())
	return c
}

func nodesListCmd() *cobra.Command {
	return &cobra.Command{
		Use:   "list",
		Short: "List configured edge nodes and connection status",
		Long: `List all nodes registered in the edge configuration file.
When the server is offline or this command is run standalone, all nodes will show their status as 'offline' or 'configured'.`,
		Example: `  iop-edge nodes list`,
		RunE: func(cmd *cobra.Command, _ []string) error {
			cfg, path, err := LoadEdgeConfig(cmd)
			if err != nil {
				return err
			}
			fmt.Fprintf(cmd.OutOrStdout(), "Config Source: %s\n\n", path)
			if len(cfg.Nodes) == 0 {
				fmt.Fprintln(cmd.OutOrStdout(), "No nodes configured.")
				return nil
			}

			nodes := make([]config.NodeDefinition, len(cfg.Nodes))
			copy(nodes, cfg.Nodes)
			sort.Slice(nodes, func(i, j int) bool {
				return nodes[i].ID < nodes[j].ID
			})

			fmt.Fprintf(cmd.OutOrStdout(), "%-25s %-20s %-40s %-12s\n", "NODE ID", "ALIAS", "TOKEN", "STATUS")
			fmt.Fprintf(cmd.OutOrStdout(), "%s\n", strings.Repeat("-", 100))
			for _, n := range nodes {
				fmt.Fprintf(cmd.OutOrStdout(), "%-25s %-20s %-40s %-12s\n", n.ID, n.Alias, n.Token, "offline (configured)")
			}
			return nil
		},
	}
}
