/*
    Hurry Curry! - a game about cooking
    Copyright (C) 2026 Hurry Curry! Contributors

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU Affero General Public License as published by
    the Free Software Foundation, version 3 of the License only.

    This program 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 Affero General Public License for more details.

    You should have received a copy of the GNU Affero General Public License
    along with this program.  If not, see <https://www.gnu.org/licenses/>.

*/
use crate::load_ini;
use anyhow::{Result, anyhow};
use std::{collections::BTreeMap, fmt::Write as W2, fs::File, io::Write, path::Path};

pub fn export_godot_csv(input_dir: &Path, output: &Path) -> Result<()> {
    let translations = input_dir
        .read_dir()?
        .flat_map(|e| {
            e.map_err(|e| anyhow!("{e}"))
                .and_then(|e| {
                    if e.file_name().to_string_lossy().ends_with(".ini") {
                        Ok(Some((
                            e.path()
                                .file_stem()
                                .ok_or(anyhow!("empty filename"))?
                                .to_string_lossy()
                                .to_string(),
                            load_ini(&e.path())?,
                        )))
                    } else {
                        Ok(None)
                    }
                })
                .transpose()
        })
        .collect::<Result<BTreeMap<_, _>>>()?;

    let langs = translations.keys().cloned().collect::<Vec<String>>();
    let mut tr_tr = BTreeMap::<String, BTreeMap<String, String>>::new();
    for (k, v) in translations {
        for (kk, vv) in v {
            tr_tr.entry(kk).or_default().insert(k.clone(), vv);
        }
    }

    File::create(output)?.write_all(
        tr_tr
            .into_iter()
            .try_fold(format!("id,{}\n", langs.join(",")), |mut a, (k, v)| {
                writeln!(
                    a,
                    "{k},{}",
                    v.values()
                        .map(serde_json::to_string)
                        .collect::<Result<Vec<_>, serde_json::Error>>()?
                        .join(",")
                )?;
                Ok::<_, anyhow::Error>(a)
            })?
            .as_bytes(),
    )?;
    Ok(())
}
