package cmd

import (
	"fmt"

	"sunhpc/internal/db"
	"sunhpc/internal/log"

	"github.com/spf13/cobra"
)

var nodeCmd = &cobra.Command{
	Use:   "node",
	Short: "节点管理",
	Long:  "管理集群节点，包括添加、删除、查询等操作",
}

var nodeListCmd = &cobra.Command{
	Use:   "list",
	Short: "列出所有节点",
	RunE: func(cmd *cobra.Command, args []string) error {
		log.Info("查询节点列表...")

		// 获取数据库实例（自动使用之前配置的路径）
		database, err := db.GetInstance()
		if err != nil {
			return fmt.Errorf("获取数据库连接失败: %v", err)
		}
		defer database.Close()

		// 执行查询
		_, err = database.Execute("SELECT id, name, rack, rank, cpus, memory, disk, os, kernel FROM nodes ORDER BY name")
		if err != nil {
			return fmt.Errorf("查询节点失败: %v", err)
		}

		// 获取所有结果
		rows, err := database.FetchAll()
		if err != nil {
			return fmt.Errorf("获取结果失败: %v", err)
		}

		if len(rows) == 0 {
			log.Info("暂无节点数据")
			return nil
		}

		// 打印结果
		fmt.Printf("%-5s %-20s %-8s %-8s %-8s %-10s %-10s %-10s\n",
			"ID", "名称", "机架", "排名", "CPU", "内存", "磁盘", "操作系统")
		fmt.Println("----------------------------------------------------------------------------------")
		for _, row := range rows {
			fmt.Printf("%-5v %-20s %-8v %-8v %-8v %-10v %-10v %-10s\n",
				row["id"], row["name"], row["rack"], row["rank"],
				row["cpus"], row["memory"], row["disk"], row["os"])
		}

		return nil
	},
}

var nodeAddCmd = &cobra.Command{
	Use:   "add <name>",
	Short: "添加节点",
	Args:  cobra.ExactArgs(1),
	RunE: func(cmd *cobra.Command, args []string) error {
		nodeName := args[0]
		log.Infof("添加节点: %s", nodeName)

		database, err := db.GetInstance()
		if err != nil {
			return fmt.Errorf("获取数据库连接失败: %v", err)
		}
		defer database.Close()

		// 插入节点
		_, err = database.Execute(
			"INSERT INTO nodes (name, rack, rank, cpus, memory, disk, os, kernel) VALUES (?, ?, ?, ?, ?, ?, ?, ?)",
			nodeName, rack, rank, cpus, memory, disk, nodeOS, kernel,
		)
		if err != nil {
			return fmt.Errorf("添加节点失败: %v", err)
		}

		log.Infof("节点 %s 添加成功", nodeName)
		return nil
	},
}

var (
	rack   int
	rank   int
	cpus   int
	memory int
	disk   int
	nodeOS string
	kernel string
)

func init() {
	// 添加子命令
	nodeCmd.AddCommand(nodeListCmd)
	nodeCmd.AddCommand(nodeAddCmd)

	// 添加参数
	nodeAddCmd.Flags().IntVar(&rack, "rack", 0, "机架号")
	nodeAddCmd.Flags().IntVar(&rank, "rank", 0, "排名")
	nodeAddCmd.Flags().IntVar(&cpus, "cpus", 0, "CPU核心数")
	nodeAddCmd.Flags().IntVar(&memory, "memory", 0, "内存大小(GB)")
	nodeAddCmd.Flags().IntVar(&disk, "disk", 0, "磁盘大小(GB)")
	nodeAddCmd.Flags().StringVar(&nodeOS, "os", "", "操作系统")
	nodeAddCmd.Flags().StringVar(&kernel, "kernel", "", "内核版本")
}
