package config

import (
	"fmt"
	"os"
	"strconv"
	"strings"

	"github.com/knadh/koanf"
	"github.com/knadh/koanf/providers/env"
	"github.com/knadh/koanf/providers/posflag"
	flag "github.com/spf13/pflag"
)

const Usage string = `openquell [options]
-t --tps  <ticks>      Set ticks per second, default 60.
-d --debug             Enable debugging output.
`

type Config struct {
	TPS        int    `koanf:"tps"`
	Loglevel   string `koanf:"loglevel"`
	Debug      bool   `koanf:"debug"` // loglevel=debug
	Startlevel int
}

func InitConfig() (*Config, error) {
	var kloader = koanf.New(".")

	flagset := flag.NewFlagSet("config", flag.ContinueOnError)
	flagset.BoolP("debug", "d", false, "enable debug log")

	flagset.Usage = func() {
		fmt.Println(Usage)
		os.Exit(0)
	}

	flagset.IntP("tps", "t", 0, "TPS")

	if err := flagset.Parse(os.Args[1:]); err != nil {
		return nil, fmt.Errorf("failed to parse program arguments: %w", err)
	}

	if err := kloader.Load(env.Provider("OC_", ".", func(s string) string {
		return strings.ReplaceAll(strings.ToLower(
			strings.TrimPrefix(s, "OC_")), "_", ".")
	}), nil); err != nil {
		return nil, fmt.Errorf("error loading environment: %w", err)
	}

	if err := kloader.Load(posflag.Provider(flagset, ".", kloader), nil); err != nil {
		return nil, fmt.Errorf("error loading flags: %w", err)
	}

	conf := &Config{}
	if err := kloader.Unmarshal("", &conf); err != nil {
		return nil, fmt.Errorf("error unmarshalling: %w", err)
	}

	switch conf.Loglevel {
	case "debug":
		conf.Debug = true
	}

	// are there any args left on commandline? if so threat them as adlinks
	if len(flagset.Args()) > 0 {
		level, err := strconv.Atoi(flagset.Args()[0])
		if err != nil {
			return nil, fmt.Errorf("failed to parse start level: %w", err)
		}

		conf.Startlevel = level
	}

	return conf, nil

}
