use eframe::egui::{self, FontData, FontDefinitions, FontFamily};

fn main() -> eframe::Result<()> {
    let options = eframe::NativeOptions::default();
    eframe::run_native(
        "spool",
        options,
        Box::new(|cc| {
            let font_status = install_cjk_fonts(&cc.egui_ctx);
            Ok(Box::new(spool::gui::app_shell::GuiApp::new(font_status)))
        }),
    )
}

fn install_cjk_fonts(ctx: &egui::Context) -> String {
    let mut fonts = FontDefinitions::default();
    let mut loaded_fonts = Vec::new();

    for (font_name, font_path) in [
        ("pingfang_sc", "/System/Library/Fonts/PingFang.ttc"),
        (
            "hiragino_sans_gb",
            "/System/Library/Fonts/Hiragino Sans GB.ttc",
        ),
        ("songti", "/System/Library/Fonts/STHeiti Light.ttc"),
        ("arial_unicode_ms", "/Library/Fonts/Arial Unicode.ttf"),
    ] {
        if let Ok(bytes) = std::fs::read(font_path) {
            fonts
                .font_data
                .insert(font_name.to_string(), FontData::from_owned(bytes).into());
            fonts
                .families
                .entry(FontFamily::Proportional)
                .or_default()
                .insert(0, font_name.to_string());
            fonts
                .families
                .entry(FontFamily::Monospace)
                .or_default()
                .push(font_name.to_string());
            loaded_fonts.push(font_name);
        }
    }

    ctx.set_fonts(fonts);

    if loaded_fonts.is_empty() {
        "未检测到可注入的中文字体，界面仍会尝试使用系统默认字体。".to_string()
    } else {
        format!("已加载中文字体：{}。", loaded_fonts.join(", "))
    }
}

#[cfg(test)]
mod tests {
    use super::install_cjk_fonts;
    use eframe::egui;

    #[test]
    fn install_cjk_fonts_returns_status_message() {
        let ctx = egui::Context::default();
        let status = install_cjk_fonts(&ctx);
        assert!(!status.trim().is_empty());
    }
}
