/*
    This file is part of jellything (https://codeberg.org/metamuffin/jellything)
    which is licensed under the GNU Affero General Public License (version 3); see /COPYING.
    Copyright (C) 2026 metamuffin <metamuffin.org>
*/
use std::{borrow::Cow, collections::HashMap, sync::LazyLock};

macro_rules! languages {
    ($($lang:literal),*) => {
        #[cfg(feature = "reload")]
        const LANGUAGES: &[&str] = &[$($lang),*];
        #[cfg(not(feature = "reload"))]
        const LANGUAGES: &[(&str, &str)] = &[$(($lang, include_str!(concat!("../../../locale/", $lang, ".ini")))),*];
    };
}
languages!("en", "de");

pub static LANG_TABLES: LazyLock<HashMap<&'static str, HashMap<&'static str, &'static str>>> =
    LazyLock::new(|| {
        let mut langs = LANGUAGES
            .iter()
            .map(|(k, v)| (*k, parse_ini(v)))
            .collect::<HashMap<_, _>>();

        let fallback = langs["en"].clone();
        for l in langs.values_mut() {
            for (k, fv) in &fallback {
                if !l.contains_key(k) {
                    l.insert(k, fv);
                }
            }
        }
        langs
    });

fn parse_ini<'a>(source: &'a str) -> HashMap<&'a str, &'a str> {
    source
        .lines()
        .filter_map(|line| {
            let (key, value) = line.split_once("=")?;
            Some((key.trim(), value.trim()))
        })
        .collect()
}

pub fn tr(lang: &str, key: &str) -> Cow<'static, str> {
    let tr_map = LANG_TABLES.get(&lang).unwrap();
    tr_map
        .get(key)
        .copied()
        .unwrap_or("MISSING TRANSLATION")
        .into()
}

pub fn escape(str: &str) -> String {
    let mut o = String::with_capacity(str.len());
    let mut last = 0;
    for (index, byte) in str.bytes().enumerate() {
        if let Some(esc) = match byte {
            b'<' => Some("&lt;"),
            b'>' => Some("&gt;"),
            b'&' => Some("&amp;"),
            b'"' => Some("&quot;"),
            _ => None,
        } {
            o += &str[last..index];
            o += esc;
            last = index + 1;
        }
    }
    o += &str[last..];
    o
}
