package cli

import (
	"os"
	"strings"
	"testing"

	"git.cloudinit.dev/coreci/orca/internal/config"
)

func TestVersionCommandExists(t *testing.T) {
	found := false
	for _, cmd := range rootCmd.Commands() {
		if cmd.Name() == "version" {
			found = true
			break
		}
	}
	if !found {
		t.Fatal("version command not registered")
	}
}

func TestRootHasAllSubcommands(t *testing.T) {
	expected := []string{"version", "init", "status", "node", "job"}
	registered := make(map[string]bool)
	for _, cmd := range rootCmd.Commands() {
		registered[cmd.Name()] = true
	}
	for _, name := range expected {
		if !registered[name] {
			t.Errorf("expected subcommand %q not registered", name)
		}
	}
}

func TestNodeSubcommands(t *testing.T) {
	expected := []string{"join", "leave", "list"}
	registered := make(map[string]bool)
	for _, cmd := range nodeCmd.Commands() {
		registered[cmd.Name()] = true
	}
	for _, name := range expected {
		if !registered[name] {
			t.Errorf("expected node subcommand %q not registered", name)
		}
	}
}

func TestJobSubcommands(t *testing.T) {
	expected := []string{"run", "list", "stop", "logs"}
	registered := make(map[string]bool)
	for _, cmd := range jobCmd.Commands() {
		registered[cmd.Name()] = true
	}
	for _, name := range expected {
		if !registered[name] {
			t.Errorf("expected job subcommand %q not registered", name)
		}
	}
}

func TestRootHelpMentionsKeyPillars(t *testing.T) {
	help := rootCmd.Long
	for _, pillar := range []string{"offline", "CLI", "Nomad", "simplicity"} {
		if !strings.Contains(strings.ToLower(help), strings.ToLower(pillar)) {
			t.Errorf("root help does not mention pillar %q", pillar)
		}
	}
}

func TestConfigFlagRegistered(t *testing.T) {
	f := rootCmd.PersistentFlags().Lookup("config")
	if f == nil {
		t.Fatal("--config persistent flag not registered")
	}
	if f.DefValue != "" {
		t.Errorf("--config default = %q, want empty", f.DefValue)
	}
}

func TestConfigFlagLoadsFile(t *testing.T) {
	dir := t.TempDir()
	cfgPath := dir + "/config.hcl"
	cfgContent := `db_path          = "` + dir + `/test.db"
listen_addr      = "127.0.0.1:9999"
ca_path          = "` + dir + `/ca.crt"
server_cert_path = "` + dir + `/server.crt"
server_key_path  = "` + dir + `/server.key"

node_capacity {
  cpu       = 4
  memory_mb = 8192
}
`
	if err := os.WriteFile(cfgPath, []byte(cfgContent), 0o644); err != nil {
		t.Fatalf("write config: %v", err)
	}

	old := configPath
	configPath = cfgPath
	defer func() { configPath = old }()

	cfg, err := config.Load(cfgPath)
	if err != nil {
		t.Fatalf("load config: %v", err)
	}
	if cfg.ListenAddr != "127.0.0.1:9999" {
		t.Errorf("listen_addr = %q, want 127.0.0.1:9999", cfg.ListenAddr)
	}
	if cfg.NodeCapacity == nil || cfg.NodeCapacity.CPU != 4 {
		t.Errorf("node_capacity.cpu not parsed, got %+v", cfg.NodeCapacity)
	}
}
