mod bridge;

use tauri::Manager;

#[cfg_attr(mobile, tauri::mobile_entry_point)]
pub fn run() {
    tauri::Builder::default()
        // Persist + restore the window's size, position and maximized state across restarts.
        .plugin(tauri_plugin_window_state::Builder::default().build())
        .plugin(tauri_plugin_notification::init())
        .plugin(tauri_plugin_dialog::init())
        .setup(|app| {
            let handle = app.handle().clone();
            // Connect the bridge on a tokio runtime, then manage it.
            tauri::async_runtime::block_on(async move {
                match bridge::Bridge::connect(handle.clone()).await {
                    Ok(bridge) => {
                        handle.manage(bridge);
                    }
                    // Don't crash the app — open the window and log. Commands will
                    // error until a daemon is reachable; start it manually
                    // (./target/debug/spaceshd) or set SPACESHD_BIN / SPACESH_SOCK.
                    Err(e) => {
                        eprintln!(
                            "spacesh: could not connect to spaceshd: {e} — \
                             start it manually or set SPACESHD_BIN/SPACESH_SOCK"
                        );
                    }
                }
            });
            Ok(())
        })
        .invoke_handler(tauri::generate_handler![
            bridge::open,
            bridge::new_surface,
            bridge::input,
            bridge::resize,
            bridge::attach,
            bridge::detach,
            bridge::status,
            bridge::close_surface,
            bridge::split_surface,
            bridge::set_ratios,
            bridge::move_surface,
            bridge::apply_preset,
            bridge::restart_surface,
            bridge::close_workspace,
            bridge::set_workspace_meta,
            bridge::create_group,
            bridge::set_group,
            bridge::delete_group,
            bridge::focus,
            bridge::set_zoom,
            bridge::event_log,
            bridge::mark_read,
            bridge::clear_events,
            bridge::health,
            bridge::which_agents,
            bridge::check_update,
            bridge::open_external,
            bridge::has_full_disk_access,
            bridge::open_full_disk_access_settings,
            bridge::list_fonts,
            bridge::get_config,
            bridge::set_config,
            bridge::read_image_data_url,
            bridge::shutdown_daemon,
        ])
        .run(tauri::generate_context!())
        .expect("error while running spacesh");
}
