package wand

import (
	"github.com/iancoleman/strcase"
	"strings"
)

type env struct {
	values        map[string][]string
	originalNames map[string]string
}

func splitEnvValue(v string) []string {
	var (
		values  []string
		escape  bool
		current []rune
	)

	for _, r := range []rune(v) {
		if escape {
			current = append(current, r)
			escape = false
			continue
		}

		if r == '\\' {
			escape = true
			continue
		}

		if r == ':' {
			values = append(values, string(current))
			current = nil
			continue
		}

		current = append(current, r)
	}

	values = append(values, string(current))
	return values
}

func readEnv(appName string, input []string) env {
	appName = strcase.ToKebab(appName)
	e := env{
		values:        make(map[string][]string),
		originalNames: make(map[string]string),
	}

	for _, i := range input {
		parts := strings.SplitN(i, "=", 2)
		if len(parts) != 2 {
			continue
		}

		key, value := parts[0], parts[1]
		key = strcase.ToKebab(key)
		if len(key) <= len(appName)+1 || !strings.HasPrefix(key, appName+"-") {
			continue
		}

		key = key[len(appName)+1:]
		e.originalNames[key] = parts[0]
		e.values[key] = splitEnvValue(value)
	}

	return e
}
