package i18n

import (
	"embed"
	"fmt"
	"os"
	"path/filepath"
	"slices"
	"strings"

	"coopcloud.tech/abra/pkg/log"
	"github.com/leonelquinteros/gotext"
)

//go:embed locales/*.mo
var assetFS embed.FS

var (
	DefaultLocale = "en"
	Locale        = DefaultLocale
	_, Mo         = LoadLocale()
	G             = Mo.Get
	GC            = Mo.GetC
)

func GetLocaleStr() string {
	locale := os.Getenv("LANG")
	if lastUnderscore := strings.LastIndex(locale, "_"); lastUnderscore != -1 {
		locale = locale[0:lastUnderscore]
	}
	return locale
}

func LoadLocale() (string, *gotext.Mo) {
	entries, err := assetFS.ReadDir("locales")
	if err != nil {
		log.Fatalf("i18n: unable to read embedded locales directory: %s", err)
	}

	var linguas []string
	for _, entry := range entries {
		if filepath.Ext(entry.Name()) == ".mo" {
			fname := entry.Name()
			fnameWithoutExt := strings.TrimSuffix(fname, filepath.Ext(fname))
			linguas = append(linguas, fnameWithoutExt)
		}
	}

	locale := GetLocaleStr()
	if locale != "" {
		if slices.Contains(linguas, locale) {
			Locale = locale
		} else {
			log.Debugf("unsupported language: %s (want: %s)", locale, strings.Join(linguas, " "))
		}
	}

	if Locale == DefaultLocale {
		return Locale, gotext.NewMo()
	}

	b, err := assetFS.ReadFile(fmt.Sprintf("locales/%s.mo", Locale))
	if err != nil {
		log.Fatalf("i18n: %s", err)
	}

	mo := gotext.NewMo()
	mo.Parse(b)

	return Locale, mo
}
