/*
    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/>.

*/
pub mod godot_csv;
pub mod json_pack;
pub mod po;

use crate::{
    godot_csv::export_godot_csv,
    json_pack::export_json_pack,
    po::{export_po, import_old_po, import_old_pot},
};
use anyhow::{Result, anyhow};
use clap::Parser;
use std::{
    collections::BTreeMap,
    fs::{File, read_to_string},
    io::Write,
    path::{Path, PathBuf},
};

#[derive(Parser)]
enum Args {
    ImportOldPot {
        input: PathBuf,
        output: PathBuf,
    },
    ImportOldPo {
        reference: PathBuf,
        input: PathBuf,
        output: PathBuf,
    },
    ExportJson {
        output: PathBuf,
        inputs: Vec<PathBuf>,
    },
    ExportJsonPack {
        output: PathBuf,
        inputs: Vec<PathBuf>,
    },
    ExportGodotCsv {
        input_dir: PathBuf,
        output: PathBuf,
    },
    ExportPo {
        #[arg(long)]
        remap_ids: Option<PathBuf>,
        output: PathBuf,
        inputs: Vec<PathBuf>,
    },
}

fn main() -> Result<()> {
    let args = Args::parse();
    match args {
        Args::ExportJson { inputs, output } => {
            let ini = export_load(&inputs)?;
            File::create(output)?.write_all(serde_json::to_string(&ini)?.as_bytes())?;
            Ok(())
        }
        Args::ExportJsonPack { inputs, output } => export_json_pack(&output, &inputs),
        Args::ExportPo {
            remap_ids,
            output,
            inputs,
        } => export_po(&inputs, &output, remap_ids),
        Args::ExportGodotCsv { input_dir, output } => export_godot_csv(&input_dir, &output),
        Args::ImportOldPo {
            reference,
            input,
            output,
        } => import_old_po(&reference, &input, &output),
        Args::ImportOldPot { input, output } => import_old_pot(&input, &output),
    }
}

fn load_ini(path: &Path) -> Result<BTreeMap<String, String>> {
    read_to_string(path)?
        .lines()
        .skip(1)
        .map(|l| {
            let (k, v) = l.split_once("=").ok_or(anyhow!("'=' missing"))?;
            Ok::<_, anyhow::Error>((k.trim_end().to_owned(), v.trim_start().replace("%n", "\n")))
        })
        .collect()
}

static NATIVE_LANGUAGE_NAMES: &[(&str, &str)] = &[
    ("en", "English"),
    ("de", "Deutsch"),
    ("fr", "Français"),
    ("nl", "Nederlands"),
    ("es", "Español"),
    ("eu", "Euskara"),
    ("ja", "日本語"),
    ("he", "עִברִית"),
    ("tr", "Türkçe"),
    ("fi", "Suomi"),
    ("ar", "العربية"),
    ("zh_Hans", "中文 (简化字)"),
    ("zh_Hant", "中文 (繁體字)"),
    ("sv", "Svenska"),
    ("pl", "Polski"),
    ("vi", "Tiếng Việt"),
    ("pt", "Português"),
    ("it", "Italiano"),
    ("ko", "한국인"),
    ("el", "ελληνικά"),
    ("ru", "русский"),
];

fn export_load(inputs: &[PathBuf]) -> Result<BTreeMap<String, String>> {
    let mut ini = BTreeMap::new();
    for path in inputs {
        let f = load_ini(path)?;
        for (k, v) in f {
            ini.entry(k).or_insert(v);
        }
    }
    for &(code, name) in NATIVE_LANGUAGE_NAMES {
        ini.insert(format!("c.settings.ui.language.{code}"), name.to_owned());
    }
    Ok(ini)
}
