package locale

import (
	"encoding/json"
)

type LocaleEntry struct {
	LanguageName  string        `json:"language_name"`
	LanguageLocal string        `json:"language_local"`
	LanguageCode  string        `json:"language_code"`
	LanguageCode2 string        `json:"language_code2"`
	LanguageCode3 string        `json:"language_code3"`
	Regions       []RegionEntry `json:"regions"`
}

type RegionEntry struct {
	Locale               string `json:"locale"`
	CountryName          string `json:"country_name"`
	CountryLocal         string `json:"country_local"`
	CountryCode          string `json:"country_code"`
	Flag                 string `json:"flag"`
	MajorRegionalVariant bool   `json:"major_regional_variant"`
	Population           int    `json:"population"`
}

func LoadFromJSON(jsonData []byte) ([]LocaleEntry, error) {
	var locales []LocaleEntry
	if err := json.Unmarshal(jsonData, &locales); err != nil {
		return nil, err
	}
	return locales, nil
}

func FindByLanguageCode(code string, locales []LocaleEntry) *LocaleEntry {
	for i := range locales {
		if locales[i].LanguageCode == code {
			return &locales[i]
		}
	}
	return nil
}

func FindByLocale(locale string, locales []LocaleEntry) (*LocaleEntry, *RegionEntry) {
	for i := range locales {
		for j := range locales[i].Regions {
			if locales[i].Regions[j].Locale == locale {
				return &locales[i], &locales[i].Regions[j]
			}
		}
	}
	return nil, nil
}

// FindAndMergeByLanguageCode finds all entries with matching language code
// and returns a merged entry with all regions combined
func FindAndMergeByLanguageCode(languageCode string, locales []LocaleEntry) *LocaleEntry {
	var mergedEntry *LocaleEntry
	var mergedRegions []RegionEntry

	for i := range locales {
		if locales[i].LanguageCode == languageCode {
			// If first entry, use it as base
			if mergedEntry == nil {
				entryCopy := locales[i]
				mergedEntry = &entryCopy
				mergedRegions = append(mergedRegions, locales[i].Regions...)
			} else {
				// Append regions from subsequent entries
				mergedRegions = append(mergedRegions, locales[i].Regions...)
			}
		}
	}

	if mergedEntry == nil {
		return nil
	}

	// Update with merged regions
	mergedEntry.Regions = mergedRegions

	return mergedEntry
}
