package config

import (
	"fmt"
	"os"
	"strconv"

	"github.com/BurntSushi/toml"
)

type Config struct {
	VM VMConfig `toml:"vm"`
}

type VMConfig struct {
	Memory string `toml:"memory"`
	CPUs   int    `toml:"cpus"`
}

func Load() (*Config, error) {
	cfg := &Config{
		VM: VMConfig{
			Memory: "30G",
			CPUs:   30,
		},
	}

	if _, err := os.Stat(ConfigFile); err == nil {
		if _, err := toml.DecodeFile(ConfigFile, cfg); err != nil {
			return nil, fmt.Errorf("failed to parse config file %s: %w", ConfigFile, err)
		}
	}

	if memEnv := os.Getenv("QVM_MEMORY"); memEnv != "" {
		cfg.VM.Memory = memEnv
	}

	if cpusEnv := os.Getenv("QVM_CPUS"); cpusEnv != "" {
		cpus, err := strconv.Atoi(cpusEnv)
		if err != nil {
			return nil, fmt.Errorf("QVM_CPUS must be a valid integer: %w", err)
		}
		cfg.VM.CPUs = cpus
	}

	return cfg, nil
}
