package config

import (
	"os"
	"path/filepath"
	"runtime"
	"time"

	"gopkg.in/yaml.v3"
)


func ConfigDir() string {
	if runtime.GOOS == "windows" {
		base := os.Getenv("ProgramData")
		if base == "" {
			base = `C:\ProgramData`
		}
		return filepath.Join(base, "vantage")
	}
	return "/etc/vantage"
}

func configPath() string { return filepath.Join(ConfigDir(), "config.yaml") }

type Config struct {
	ServerURL    string        `yaml:"server_url"`
	ServerID     string        `yaml:"server_id"`
	PreRegToken  string        `yaml:"pre_reg_token"`
	AgentToken   string        `yaml:"agent_token"`
	PollInterval time.Duration `yaml:"poll_interval"`
	TLS          bool          `yaml:"tls"`
}

func Load() (*Config, error) {
	data, err := os.ReadFile(configPath())
	if err != nil {
		return nil, err
	}
	var cfg Config
	if err := yaml.Unmarshal(data, &cfg); err != nil {
		return nil, err
	}
	if cfg.PollInterval == 0 {
		cfg.PollInterval = 30 * time.Second
	}
	return &cfg, nil
}

func Save(cfg *Config) error {
	data, err := yaml.Marshal(cfg)
	if err != nil {
		return err
	}
	if err := os.MkdirAll(ConfigDir(), 0700); err != nil {
		return err
	}
	return os.WriteFile(configPath(), data, 0600)
}
