package config

import (
	"caltrack/types"
	"os"
	"path/filepath"

	"github.com/BurntSushi/toml"
)

func DefaultConfig() types.Config {
	return types.Config{
		CurrentWeightKg: 80.0,
		TargetWeightKg:  70.0,
		HeightCm:        175,
		Age:             30,
		Sex:             "male",
		ActivityLevel:   "moderate",
		WeeklyLossKg:    0.5,
		ListenAddr:      ":8080",
	}
}

func DataDir() (string, error) {
	if dir := os.Getenv("CALTRACK_DATA_DIR"); dir != "" {
		return dir, nil
	}
	home, err := os.UserHomeDir()
	if err != nil {
		return "", err
	}
	return filepath.Join(home, ".config", "caltrack"), nil
}

func ConfigPath() (string, error) {
	dir, err := DataDir()
	if err != nil {
		return "", err
	}
	return filepath.Join(dir, "config.toml"), nil
}

func Load() (types.Config, error) {
	cfg := DefaultConfig()

	path, err := ConfigPath()
	if err != nil {
		return cfg, err
	}

	if _, err := os.Stat(path); os.IsNotExist(err) {
		return cfg, nil
	}

	_, err = toml.DecodeFile(path, &cfg)
	if err != nil {
		return cfg, err
	}

	if cfg.ListenAddr == "" {
		cfg.ListenAddr = ":8080"
	}

	return cfg, nil
}

func Save(cfg types.Config) error {
	path, err := ConfigPath()
	if err != nil {
		return err
	}

	if err := os.MkdirAll(filepath.Dir(path), 0755); err != nil {
		return err
	}

	f, err := os.Create(path)
	if err != nil {
		return err
	}
	defer f.Close()

	return toml.NewEncoder(f).Encode(cfg)
}
