package wizard

import (
	"errors"
	"net"
	"os"
	"sunhpc/pkg/database"
	"sunhpc/pkg/logger"
	"sunhpc/pkg/utils"

	"github.com/BurntSushi/toml"
)

// 配置项映射：定义每个配置项对应的表名、键名
type ConfigMapping struct {
	Title string `toml:"title"`
	Base  struct {
		ClusterName  string `toml:"cluster_name"`
		Country      string `toml:"country"`
		State        string `toml:"state"`
		City         string `toml:"city"`
		HomePage     string `toml:"homepage"`
		Contact      string `toml:"contact"`
		License      string `toml:"license"`
		BaseDir      string `toml:"base_dir"`
		WorkDir      string `toml:"work_dir"`
		DistroDir    string `toml:"distro_dir"`
		Partition    string `toml:"partition"`
		Distribution string `toml:"distribution"`
		Timezone     string `toml:"timezone"`
		SafePort     string `toml:"safe_port"`
		SafeDirs     string `toml:"safe_dirs"`
		SafeSecurity string `toml:"safe_security"`
		PluginDirs   string `toml:"plugin_dirs"`
		PluginPort   string `toml:"plugin_port"`
		GangliaAddr  string `toml:"ganglia_addr"`
	} `toml:"base"`
	Pxelinux struct {
		NextServer  string `toml:"next_server"`
		PxeFilename string `toml:"pxe_filename"`
		PxeLinuxDir string `toml:"pxelinux_dir"`
		BootArgs    string `toml:"boot_args"`
	} `toml:"pxelinux"`
	Public struct {
		PublicHostname  string `toml:"public_hostname"`
		PublicInterface string `toml:"public_interface"`
		PublicAddress   string `toml:"public_address"`
		PublicNetmask   string `toml:"public_netmask"`
		PublicGateway   string `toml:"public_gateway"`
		PublicNetwork   string `toml:"public_network"`
		PublicDomain    string `toml:"public_domain"`
		PublicCIDR      string `toml:"public_cidr"`
		PublicDNS       string `toml:"public_dns"`
		PublicMac       string `toml:"public_mac"`
		PublicMTU       string `toml:"public_mtu"`
		PublicNTP       string `toml:"public_ntp"`
	} `toml:"public"`
	Private struct {
		PrivateHostname  string `toml:"private_hostname"`
		PrivateInterface string `toml:"private_interface"`
		PrivateAddress   string `toml:"private_address"`
		PrivateNetmask   string `toml:"private_netmask"`
		PrivateNetwork   string `toml:"private_network"`
		PrivateDomain    string `toml:"private_domain"`
		PrivateCIDR      string `toml:"private_cidr"`
		PrivateMac       string `toml:"private_mac"`
		PrivateMTU       string `toml:"private_mtu"`
	} `toml:"private"`
}

func NewConfigWithDefault() *ConfigMapping {
	return &ConfigMapping{
		Title: "Cluster Configuration",
		Base: struct {
			ClusterName  string `toml:"cluster_name"`
			Country      string `toml:"country"`
			State        string `toml:"state"`
			City         string `toml:"city"`
			HomePage     string `toml:"homepage"`
			Contact      string `toml:"contact"`
			License      string `toml:"license"`
			BaseDir      string `toml:"base_dir"`
			WorkDir      string `toml:"work_dir"`
			DistroDir    string `toml:"distro_dir"`
			Partition    string `toml:"partition"`
			Distribution string `toml:"distribution"`
			Timezone     string `toml:"timezone"`
			SafePort     string `toml:"safe_port"`
			SafeDirs     string `toml:"safe_dirs"`
			SafeSecurity string `toml:"safe_security"`
			PluginDirs   string `toml:"plugin_dirs"`
			PluginPort   string `toml:"plugin_port"`
			GangliaAddr  string `toml:"ganglia_addr"`
		}{
			ClusterName:  "SunHPC_Cluster",
			Country:      "CN",
			State:        "Beijing",
			City:         "Beijing",
			HomePage:     "https://www.sunhpc.com",
			Contact:      "admin@sunhpc.com",
			License:      "MIT",
			BaseDir:      "install",
			WorkDir:      "/export",
			DistroDir:    "/export/sunhpc",
			Partition:    "default",
			Distribution: "sunhpc-dist",
			Timezone:     "Asia/Shanghai",
			SafePort:     "372",
			SafeDirs:     "safe.d",
			SafeSecurity: "safe-security",
			PluginDirs:   "/etc/sunhpc/plugin",
			PluginPort:   "12123",
			GangliaAddr:  "224.0.0.3",
		},
		Pxelinux: struct {
			NextServer  string `toml:"next_server"`
			PxeFilename string `toml:"pxe_filename"`
			PxeLinuxDir string `toml:"pxelinux_dir"`
			BootArgs    string `toml:"boot_args"`
		}{
			NextServer:  "192.168.1.1",
			PxeFilename: "pxelinux.0",
			PxeLinuxDir: "/tftpboot/pxelinux",
			BootArgs:    "net.ifnames=0 biosdevname=0",
		},
		Public: struct {
			PublicHostname  string `toml:"public_hostname"`
			PublicInterface string `toml:"public_interface"`
			PublicAddress   string `toml:"public_address"`
			PublicNetmask   string `toml:"public_netmask"`
			PublicGateway   string `toml:"public_gateway"`
			PublicNetwork   string `toml:"public_network"`
			PublicDomain    string `toml:"public_domain"`
			PublicCIDR      string `toml:"public_cidr"`
			PublicDNS       string `toml:"public_dns"`
			PublicMac       string `toml:"public_mac"`
			PublicMTU       string `toml:"public_mtu"`
			PublicNTP       string `toml:"public_ntp"`
		}{
			PublicHostname:  "cluster.hpc.org",
			PublicInterface: "eth0",
			PublicAddress:   "",
			PublicNetmask:   "",
			PublicGateway:   "",
			PublicNetwork:   "",
			PublicDomain:    "hpc.org",
			PublicCIDR:      "",
			PublicDNS:       "",
			PublicMac:       "00:11:22:33:44:55",
			PublicMTU:       "1500",
			PublicNTP:       "pool.ntp.org",
		},
		Private: struct {
			PrivateHostname  string `toml:"private_hostname"`
			PrivateInterface string `toml:"private_interface"`
			PrivateAddress   string `toml:"private_address"`
			PrivateNetmask   string `toml:"private_netmask"`
			PrivateNetwork   string `toml:"private_network"`
			PrivateDomain    string `toml:"private_domain"`
			PrivateCIDR      string `toml:"private_cidr"`
			PrivateMac       string `toml:"private_mac"`
			PrivateMTU       string `toml:"private_mtu"`
		}{
			PrivateHostname:  "sunhpc",
			PrivateInterface: "eth1",
			PrivateAddress:   "172.16.9.254",
			PrivateNetmask:   "255.255.255.0",
			PrivateNetwork:   "172.16.9.0",
			PrivateDomain:    "example.com",
			PrivateCIDR:      "172.16.9.0/24",
			PrivateMac:       "00:11:22:33:44:66",
			PrivateMTU:       "1500",
		},
	}
}

func loadConfig() (*ConfigMapping, error) {
	configs := NewConfigWithDefault()
	cfgfile := "/etc/sunhpc/config.toml"

	// 尝试解析配置文件
	if _, err := toml.DecodeFile(cfgfile, configs); err != nil {
		if errors.Is(err, os.ErrNotExist) {
			// 文件不存在，直接返回默认配置
			logger.Infof("Config file %s not exist, use default config", cfgfile)
			return configs, nil
		}
		// 其他错误，返回错误
		logger.Debugf("[DEBUG] Parse config file %s failed: %v", cfgfile, err)
		return nil, err
	}

	logger.Infof("Load config file %s success", cfgfile)
	return configs, nil
}

// saveConfig 入口函数：保存所有配置到数据库
func (m *model) saveConfig() error {

	conn, err := database.GetDB() // 假设database包已实现getDB()获取连接
	if err != nil {
		logger.Errorf("Database connection failed: %v", err)
		return err
	}
	defer conn.Close()

	m.force = false // 初始化全量覆盖标识

	config, err := loadConfig()
	if err != nil {
		logger.Debugf("[DEBUG] Load config file failed: %v", err)
		return err
	}

	t_value := m.config.PrivateIPAddress
	c_value := config.Private.PrivateAddress

	logger.Debugf("t_value: %s\n", t_value)
	logger.Debugf("c_value: %s\n", c_value)

	logger.Debugf("config.Base.ClusterName: %s\n", config.Base.ClusterName)

	return nil
}

// 获取系统网络接口
func getNetworkInterfaces() []string {
	// 实现获取系统网络接口的逻辑
	// 例如：使用 net.Interface() 函数获取系统网络接口
	// 返回一个字符串切片，包含系统网络接口的名称
	interfaces, err := net.Interfaces()
	if err != nil {
		return []string{utils.NoAvailableNetworkInterfaces}
	}

	var result []string
	for _, iface := range interfaces {
		// 跳过 loopback 接口
		if iface.Flags&net.FlagLoopback != 0 {
			continue
		}
		result = append(result, iface.Name)
	}

	if len(result) == 0 {
		return []string{utils.NoAvailableNetworkInterfaces}
	}
	return result
}
