package config

import (
	"fmt"

	"github.com/ilyakaznacheev/cleanenv"
)

type Host struct {
	Hostname string   `yaml:"hostname"`
	Ip       string   `yaml:"ip"`
	Roles    []string `yaml:"roles"`
	User     string   `yaml:"user"`
	Password string   `yaml:"password"`
}

type Config struct {
	WorkDir     string
	Verbose     bool
	Credentials struct {
		User            string `yaml:"user"`
		Password        string `yaml:"password"`
		AskSudoPassword bool   `yaml:"ask_sudo_password"`
		PrivateKeyFile  string `yaml:"private_key_file"`
	} `yaml:"credentials"`

	Hosts []Host `yaml:"hosts"`

	Orchestrator Orchestrator `yaml:"orchestrator"`

	Modules struct {
		AdminPassword          string         `yaml:"admin_password"`
		AdditionalRepositories interface{}    `yaml:"additional_repositories"`
		Additional             Additional     `yaml:"additional"`
		Observability          Observability  `yaml:"observability"`
		Registry               Registry       `yaml:"registry"`
		Cicd                   Cicd           `yaml:"cicd"`
		SecretsStorage         SecretsStorage `yaml:"secrets_storage"`
	} `yaml:"modules"`

	Repositories string
	Releases     string
}

var instance *Config

func CreateConfig(configPath string, workDir string, password string) *Config {
	instance = &Config{}
	instance.WorkDir = workDir

	if err := cleanenv.ReadConfig(configPath, instance); err != nil {
		helper, _ := cleanenv.GetDescription(instance, nil)
		panic(fmt.Sprintf("%s\n%s", helper, err))
	}

	if password != "" {
		instance.Credentials.Password = password
	}

	generateCreds(instance)

	return instance
}

func GetConfig() *Config {
	return instance
}
