use std::sync::{Arc, Mutex};
use tauri::Manager;
use tauri_plugin_shell::process::CommandChild;
use tokio_util::sync::CancellationToken;

mod sidecar;
mod tray;

pub struct BackendState {
    pub port: Arc<Mutex<Option<u16>>>,
    pub child: Arc<Mutex<Option<CommandChild>>>,
    pub cancel_token: Arc<Mutex<Option<CancellationToken>>>,
}

#[cfg_attr(mobile, tauri::mobile_entry_point)]
pub fn run() {
    tauri::Builder::default()
        .plugin(tauri_plugin_shell::init())
        .plugin(tauri_plugin_single_instance::init(|app, _args, _cwd| {
            if let Some(w) = app.get_webview_window("main") {
                let _ = w.show();
                let _ = w.set_focus();
            }
        }))
        .plugin(tauri_plugin_process::init())
        .manage(BackendState {
            port: Arc::new(Mutex::new(None)),
            child: Arc::new(Mutex::new(None)),
            cancel_token: Arc::new(Mutex::new(None)),
        })
        .invoke_handler(tauri::generate_handler![
            sidecar::start_backend,
            sidecar::get_backend_port,
            sidecar::stop_backend,
            sidecar::check_backend_health,
        ])
        .setup(|app| {
            tray::create_tray(app)?;
            Ok(())
        })
        .on_window_event(|window, event| {
            // Close-to-tray: hide main window instead of closing
            if window.label() == "main" {
                if let tauri::WindowEvent::CloseRequested { api, .. } = event {
                    api.prevent_close();
                    let _ = window.hide();
                }
            }
        })
        .run(tauri::generate_context!())
        .expect("error while running tauri application");
}
