/*
 * ministream - minimal (subset) appstream metadata parser
 * Copyright (c) 2026  Florian Leander Singer <sp1rit@disroot.org>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, see <https://www.gnu.org/licenses/>.
 */

#include "ministream-priv.h"

gchar* ms_get_current_locale(void) {
	/* use LANGUAGE, LC_ALL, LC_MESSAGES and LANG */
	const gchar* const* locale_names = g_get_language_names();
	gchar* locale = NULL;
	if (g_strstr_len(locale_names[0], -1, "_") == NULL) {
		/* The locale doesn't have a region code - see if LANG has more to offer. */
		const gchar* env_lang = g_getenv("LANG");
		if ((env_lang != NULL) && (g_strstr_len(env_lang, -1, "_") != NULL))
			locale = g_strdup(env_lang);
	}
	if (locale == NULL)
		locale = g_strdup(locale_names[0]);
	if (locale == NULL)
		locale = g_strdup("C");

	/* return active locale without UTF-8 suffix, UTF-8 is default in AppStream */
	if (g_str_has_suffix(locale, ".UTF-8"))
		locale[strlen(locale) - strlen(".UTF-8")] = '\0';

	gchar *variant = strstr(locale, "@");
	const gchar* suffix = NULL;
	if (variant) {
		if (g_str_has_prefix(variant, "@cyrillic"))
			suffix = "-Cyrl";
		else if (g_str_has_prefix (variant, "@devanagari"))
			suffix = "-Deva";
		else if (g_str_has_prefix (variant, "@latin"))
			suffix = "-Latn";
		else if (g_str_has_prefix (variant, "@shaw"))
			suffix = "-Shaw";
		else if (!g_str_has_prefix (variant, "@euro"))
			suffix = "-euro"; // ???	
		variant[0] = '\0';
	}

	GString* bcp47 = g_string_new_take(locale);
	g_string_replace(bcp47, "_", "-", 0);
	if (suffix)
		g_string_append(bcp47, suffix);
	return g_string_free_and_steal(bcp47);
}

guint ms_locale_score(const gchar* lhs, const gchar* rhs) {
	if (!lhs || !rhs)
		return 0;

	guint segments = 0;
	for (gsize i = 0; ; i++) {
		if ((lhs[i] == '-' || lhs[i] == '\0') && (rhs[i] == '-' || rhs[i] == '\0'))
			++segments;
		if (lhs[i] == '\0' || rhs[i] == '\0')
			break;
		if (lhs[i] != rhs[i])
			return 0;
	}
	return segments;
}
