extern crate core;
use crate::encoding::read_response_body;
use crate::error::Error::GenericError;
use crate::error::Result;
use crate::grpc::{build_metadata, metadata_to_map};
use crate::http_request::send_http_request;
use crate::import::{import_data, import_url};
use crate::models_ext::{BlobManagerExt, QueryManagerExt};
use crate::notifications::YaakNotifier;
use crate::render::{render_grpc_request, render_template};
use crate::updates::{UpdateMode, UpdateTrigger, YaakUpdater};
use crate::uri_scheme::handle_deep_link;
use error::Result as YaakResult;
use eventsource_client::{EventParser, SSE};
use log::{debug, error, info, warn};
use std::path::PathBuf;
use std::str::FromStr;
use std::sync::Arc;
use std::time::Duration;
use std::{fs, panic};
use tauri::path::BaseDirectory;
use tauri::{AppHandle, Emitter, RunEvent, State, WebviewWindow, is_dev};
use tauri::{Listener, Runtime};
use tauri::{Manager, WindowEvent};
use tauri_plugin_deep_link::DeepLinkExt;
use tauri_plugin_log::fern::colors::ColoredLevelConfig;
use tauri_plugin_log::{Builder, Target, TargetKind, log};
use tokio::sync::Mutex;
use tokio::task::block_in_place;
use tokio::time;
use yaak::send::ResponseBody;
use yaak_commands::responses::locate_response_body;
use yaak_commands::resolve::resolve_grpc_request;
use yaak_common::command::new_checked_command;
use yaak_crypto::manager::EncryptionManager;
use yaak_grpc::manager::{GrpcConfig, GrpcHandle};
use yaak_grpc::{Code, ServiceDefinition};
use yaak_mac_window::AppHandleMacWindowExt;
use yaak_models::models::{
    CookieJar, Environment, GrpcConnection, GrpcConnectionState, GrpcEvent,
    GrpcEventType, HttpRequest, HttpResponse, HttpResponseState, Workspace,
};
use yaak_models::util::{BatchUpsertResult, UpdateSource};
use yaak_plugins::events::{
    Color, ErrorResponse, FilterResponse, InternalEvent, InternalEventPayload, PluginContext,
    RenderPurpose, ShowToastRequest,
};
use yaak_plugins::manager::PluginManager;
use yaak_plugins::template_callback::PluginTemplateCallback;
use yaak_rpc_schema::{AppMetaData, EphemeralHttpResponse};
use yaak_sse::sse::ServerSentEvent;
use yaak_tauri_utils::window::WorkspaceWindowTrait;
use yaak_templates::strip_json_comments::strip_json_comments;
use yaak_templates::{RenderErrorBehavior, RenderOptions};
use yaak_tls::find_client_certificate;

mod encoding;
mod error;
mod feedback;
mod git_ext;
mod git_watcher;
mod grpc;
mod history;
mod http_request;
mod import;
mod models_ext;
mod notifications;
mod plugin_events;
mod plugins_ext;
mod render;
mod restart;
mod rpc_ext;
mod sync_ext;
mod updates;
mod uri_scheme;
mod window_menu;
mod ws_ext;

#[cfg(not(any(feature = "cef", feature = "wry")))]
compile_error!("Enable one Tauri runtime feature: `cef` or `wry`.");

#[cfg(feature = "cef")]
type TauriRuntime = tauri::Cef;
#[cfg(all(not(feature = "cef"), feature = "wry"))]
type TauriRuntime = tauri::Wry;

fn setup_window_menu<R: Runtime>(win: &WebviewWindow<R>) -> Result<()> {
    #[allow(unused_variables)]
    let menu = window_menu::app_menu(win.app_handle())?;

    // This causes the window to not be clickable (in AppImage), so disable on Linux
    #[cfg(not(target_os = "linux"))]
    win.app_handle().set_menu(menu).expect("Failed to set app menu");

    let webview_window = win.clone();
    win.on_menu_event(move |w, event| {
        use tauri::{Emitter, LogicalSize, PhysicalSize};
        use tauri_plugin_opener::OpenerExt;

        if !w.is_focused().unwrap() {
            return;
        }

        let event_id = event.id().0.as_str();
        match event_id {
            "hacked_quit" => {
                w.webview_windows().iter().for_each(|(_, w)| {
                    info!("Closing window {}", w.label());
                    let _ = w.close();
                });
            }
            "close" => w.close().unwrap(),
            "zoom_reset" => w.emit("zoom_reset", true).unwrap(),
            "zoom_in" => w.emit("zoom_in", true).unwrap(),
            "zoom_out" => w.emit("zoom_out", true).unwrap(),
            "settings" => w.emit("settings", true).unwrap(),
            "open_feedback" => {
                if let Err(e) =
                    w.app_handle().opener().open_url("https://yaak.app/feedback", None::<&str>)
                {
                    warn!("Failed to open feedback {e:?}")
                }
            }

            // Commands for development
            "dev.reset_size" => webview_window.set_size(LogicalSize::new(1100.0, 600.0)).unwrap(),
            "dev.reset_size_16x9" => {
                let width = webview_window.outer_size().unwrap().width;
                let height = width * 9 / 16;
                webview_window.set_size(PhysicalSize::new(width, height)).unwrap()
            }
            "dev.reset_size_16x10" => {
                let width = webview_window.outer_size().unwrap().width;
                let height = width * 10 / 16;
                webview_window.set_size(PhysicalSize::new(width, height)).unwrap()
            }
            "dev.refresh" => webview_window.eval("location.reload()").unwrap(),
            "dev.generate_theme_css" => {
                w.emit("generate_theme_css", true).unwrap();
            }
            "dev.toggle_devtools" => {
                if webview_window.is_devtools_open() {
                    webview_window.close_devtools();
                } else {
                    webview_window.open_devtools();
                }
            }
            _ => {}
        }
    });

    Ok(())
}

fn initial_appearance_script<R: Runtime>(app_handle: &AppHandle<R>) -> Option<String> {
    // Only report the appearance the OS prefers. The frontend needs it to resolve the
    // "automatic" setting, so the configured appearance is never a substitute for it.
    //
    // NOTE: The value comes from the watcher state, not a fresh detection, so the frontend
    //  only ever sees a snapshot when the change events that keep it fresh are also flowing.
    let state = app_handle.try_state::<yaak_system_appearance::SystemAppearanceState>()?;
    let appearance = state.last_appearance()?;
    Some(yaak_system_appearance::initialization_script(appearance))
}

/// Extension trait for easily creating a PluginContext from a WebviewWindow
pub trait PluginContextExt<R: Runtime> {
    fn plugin_context(&self) -> PluginContext;
}

impl<R: Runtime> PluginContextExt<R> for WebviewWindow<R> {
    fn plugin_context(&self) -> PluginContext {
        PluginContext::new(Some(self.label().to_string()), self.workspace_id())
    }
}

async fn cmd_metadata<R: Runtime>(app_handle: AppHandle<R>) -> YaakResult<AppMetaData> {
    let app_data_dir = app_handle.path().app_data_dir()?;
    let app_log_dir = app_handle.path().app_log_dir()?;
    let vendored_plugin_dir =
        app_handle.path().resolve("vendored/plugins", BaseDirectory::Resource)?;
    let default_project_dir = app_handle.path().home_dir()?.join("YaakProjects");
    let cli_version = detect_cli_version().await;
    Ok(AppMetaData {
        is_dev: is_dev(),
        version: app_handle.package_info().version.to_string(),
        cli_version,
        name: app_handle.package_info().name.to_string(),
        app_data_dir: app_data_dir.to_string_lossy().to_string(),
        app_log_dir: app_log_dir.to_string_lossy().to_string(),
        vendored_plugin_dir: vendored_plugin_dir.to_string_lossy().to_string(),
        default_project_dir: default_project_dir.to_string_lossy().to_string(),
        feature_license: cfg!(feature = "license"),
        feature_updater: cfg!(feature = "updater"),
    })
}

async fn detect_cli_version() -> Option<String> {
    detect_cli_version_for_binary("yaak").await
}

async fn detect_cli_version_for_binary(program: &str) -> Option<String> {
    let mut cmd = new_checked_command(program, "--version").await.ok()?;
    let out = cmd.arg("--version").output().await.ok()?;
    if !out.status.success() {
        return None;
    }

    let line = String::from_utf8(out.stdout).ok()?;
    let line = line.lines().find(|l| !l.trim().is_empty())?.trim();
    let mut parts = line.split_whitespace();
    let _name = parts.next();
    Some(parts.next().unwrap_or(line).to_string())
}

async fn cmd_send_feedback<R: Runtime>(
    app_handle: AppHandle<R>,
    feature: String,
    text: String,
) -> YaakResult<()> {
    feedback::send_feedback(&app_handle, feature, text).await;
    Ok(())
}

async fn cmd_dismiss_notification<R: Runtime>(
    window: WebviewWindow<R>,
    notification_id: &str,
    yaak_notifier: State<'_, Mutex<YaakNotifier>>,
) -> YaakResult<()> {
    Ok(yaak_notifier.lock().await.seen(&window, notification_id).await?)
}

async fn cmd_grpc_reflect<R: Runtime>(
    request_id: &str,
    environment_id: Option<&str>,
    proto_files: Vec<String>,
    window: WebviewWindow<R>,
    app_handle: AppHandle<R>,
    grpc_handle: State<'_, Mutex<GrpcHandle>>,
) -> YaakResult<Vec<ServiceDefinition>> {
    let unrendered_request = app_handle.db().get_grpc_request(request_id)?;
    let (resolved_request, auth_context_id) =
        resolve_grpc_request(&window.db(), &unrendered_request)?;

    let environment_chain = app_handle.db().resolve_environments(
        &unrendered_request.workspace_id,
        unrendered_request.folder_id.as_deref(),
        environment_id,
    )?;
    let resolved_settings =
        app_handle.db().resolve_settings_for_grpc_request(&unrendered_request)?;

    let plugin_manager = Arc::new((*app_handle.state::<PluginManager>()).clone());
    let encryption_manager = Arc::new((*app_handle.state::<EncryptionManager>()).clone());
    let req = render_grpc_request(
        &resolved_request,
        environment_chain,
        &PluginTemplateCallback::new(
            plugin_manager,
            encryption_manager,
            &PluginContext::new(Some(window.label().to_string()), window.workspace_id()),
            RenderPurpose::Send,
        ),
        &RenderOptions { error_behavior: RenderErrorBehavior::Throw },
    )
    .await?;

    let uri = safe_uri(&req.url);
    let metadata = build_metadata(&window, &req, &auth_context_id).await?;
    let settings = window.db().get_settings();
    let client_certificate =
        find_client_certificate(req.url.as_str(), &settings.client_certificates);
    let proto_files: Vec<PathBuf> =
        proto_files.iter().map(|p| PathBuf::from_str(p).unwrap()).collect();

    // Always invalidate cached pool when this command is called, to force re-reflection
    let mut handle = grpc_handle.lock().await;
    handle.invalidate_pool(&req.id, &uri, &proto_files);

    Ok(handle
        .services(
            &req.id,
            &uri,
            &proto_files,
            &metadata,
            resolved_settings.validate_certificates.value,
            client_certificate,
            resolved_settings.request_message_size.value,
        )
        .await
        .map_err(|e| GenericError(e.to_string()))?)
}

async fn cmd_grpc_go<R: Runtime>(
    request_id: &str,
    environment_id: Option<&str>,
    proto_files: Vec<String>,
    app_handle: AppHandle<R>,
    window: WebviewWindow<R>,
    grpc_handle: State<'_, Mutex<GrpcHandle>>,
) -> YaakResult<String> {
    let unrendered_request = app_handle.db().get_grpc_request(request_id)?;
    let (resolved_request, auth_context_id) =
        resolve_grpc_request(&window.db(), &unrendered_request)?;
    let environment_chain = app_handle.db().resolve_environments(
        &unrendered_request.workspace_id,
        unrendered_request.folder_id.as_deref(),
        environment_id,
    )?;
    let resolved_settings =
        app_handle.db().resolve_settings_for_grpc_request(&unrendered_request)?;

    let plugin_manager = Arc::new((*app_handle.state::<PluginManager>()).clone());
    let encryption_manager = Arc::new((*app_handle.state::<EncryptionManager>()).clone());
    let request = render_grpc_request(
        &resolved_request,
        environment_chain.clone(),
        &PluginTemplateCallback::new(
            plugin_manager.clone(),
            encryption_manager.clone(),
            &PluginContext::new(Some(window.label().to_string()), window.workspace_id()),
            RenderPurpose::Send,
        ),
        &RenderOptions { error_behavior: RenderErrorBehavior::Throw },
    )
    .await?;

    let metadata = build_metadata(&window, &request, &auth_context_id).await?;

    // Find matching client certificate for this URL
    let settings = app_handle.db().get_settings();
    let client_cert = find_client_certificate(&request.url, &settings.client_certificates);

    let conn = app_handle.db().upsert_grpc_connection(
        &GrpcConnection {
            workspace_id: request.workspace_id.clone(),
            request_id: request.id.clone(),
            status: -1,
            elapsed: 0,
            state: GrpcConnectionState::Initialized,
            url: request.url.clone(),
            ..Default::default()
        },
        &UpdateSource::from_window_label(window.label()),
    )?;

    let conn_id = conn.id.clone();

    let base_msg = GrpcEvent {
        workspace_id: request.clone().workspace_id,
        request_id: request.clone().id,
        connection_id: conn.clone().id,
        ..Default::default()
    };

    let (in_msg_tx, in_msg_rx) = tauri::async_runtime::channel::<String>(16);
    let maybe_in_msg_tx = std::sync::Mutex::new(Some(in_msg_tx.clone()));
    let (cancelled_tx, mut cancelled_rx) = tokio::sync::watch::channel(false);

    let uri = safe_uri(&request.url);

    let in_msg_stream = tokio_stream::wrappers::ReceiverStream::new(in_msg_rx);

    let (service, method) = {
        let req = request.clone();
        match (req.service, req.method) {
            (Some(service), Some(method)) => (service, method),
            _ => return Err(GenericError("Service and method are required".to_string())),
        }
    };

    let start = std::time::Instant::now();
    let connection = grpc_handle
        .lock()
        .await
        .connect(
            &request.clone().id,
            uri.as_str(),
            &proto_files.iter().map(|p| PathBuf::from_str(p).unwrap()).collect(),
            &metadata,
            resolved_settings.validate_certificates.value,
            client_cert.clone(),
            resolved_settings.request_message_size.value,
        )
        .await;

    let connection = match connection {
        Ok(c) => c,
        Err(err) => {
            app_handle.db().upsert_grpc_connection(
                &GrpcConnection {
                    elapsed: start.elapsed().as_millis() as i32,
                    error: Some(err.to_string()),
                    state: GrpcConnectionState::Closed,
                    ..conn.clone()
                },
                &UpdateSource::from_window_label(window.label()),
            )?;
            return Ok(conn_id);
        }
    };

    let method_desc =
        connection.method(&service, &method).await.map_err(|e| GenericError(e.to_string()))?;

    #[derive(serde::Deserialize)]
    enum IncomingMsg {
        Message(String),
        Cancel,
        Commit,
    }

    let cb = {
        let cancelled_rx = cancelled_rx.clone();
        let environment_chain = environment_chain.clone();
        let window = window.clone();
        let plugin_manager = plugin_manager.clone();
        let encryption_manager = encryption_manager.clone();

        move |ev: tauri::Event| {
            if *cancelled_rx.borrow() {
                // Stream is canceled
                return;
            }

            let mut maybe_in_msg_tx = maybe_in_msg_tx.lock().expect("previous holder not to panic");
            let in_msg_tx = if let Some(in_msg_tx) = maybe_in_msg_tx.as_ref() {
                in_msg_tx
            } else {
                // This would mean that the stream is already committed because
                // we have already dropped the sending half
                return;
            };

            match serde_json::from_str::<IncomingMsg>(ev.payload()) {
                Ok(IncomingMsg::Message(msg)) => {
                    let window = window.clone();
                    let environment_chain = environment_chain.clone();
                    let plugin_manager = plugin_manager.clone();
                    let encryption_manager = encryption_manager.clone();
                    let msg = block_in_place(|| {
                        tauri::async_runtime::block_on(async {
                            let result = render_template(
                                msg.as_str(),
                                environment_chain,
                                &PluginTemplateCallback::new(
                                    plugin_manager,
                                    encryption_manager,
                                    &PluginContext::new(
                                        Some(window.label().to_string()),
                                        window.workspace_id(),
                                    ),
                                    RenderPurpose::Send,
                                ),
                                &RenderOptions { error_behavior: RenderErrorBehavior::Throw },
                            )
                            .await;
                            result.expect("Failed to render template")
                        })
                    });
                    let msg = strip_json_comments(&msg);
                    in_msg_tx.try_send(msg.clone()).unwrap();
                }
                Ok(IncomingMsg::Commit) => {
                    maybe_in_msg_tx.take();
                }
                Ok(IncomingMsg::Cancel) => {
                    cancelled_tx.send_replace(true);
                }
                Err(e) => {
                    error!("Failed to parse gRPC message: {:?}", e);
                }
            }
        }
    };
    let event_handler = app_handle.listen_any(format!("grpc_client_msg_{}", conn.id).as_str(), cb);

    let grpc_listen = {
        let window = window.clone();
        let app_handle = app_handle.clone();
        let base_event = base_msg.clone();
        let environment_chain = environment_chain.clone();
        let req = request.clone();
        let msg = if req.message.is_empty() { "{}".to_string() } else { req.message };
        let msg = render_template(
            msg.as_str(),
            environment_chain,
            &PluginTemplateCallback::new(
                plugin_manager.clone(),
                encryption_manager.clone(),
                &PluginContext::new(Some(window.label().to_string()), window.workspace_id()),
                RenderPurpose::Send,
            ),
            &RenderOptions { error_behavior: RenderErrorBehavior::Throw },
        )
        .await?;
        let msg = strip_json_comments(&msg);

        app_handle.db().upsert_grpc_event(
            &GrpcEvent {
                content: format!("Connecting to {}", req.url),
                event_type: GrpcEventType::ConnectionStart,
                metadata: metadata.clone(),
                ..base_event.clone()
            },
            &UpdateSource::from_window_label(window.label()),
        )?;

        async move {
            // Create callback for streaming methods that handles both success and error
            let on_message = {
                let app_handle = app_handle.clone();
                let base_event = base_event.clone();
                let window_label = window.label().to_string();
                move |result: std::result::Result<String, String>| match result {
                    Ok(msg) => {
                        let _ = app_handle.db().upsert_grpc_event(
                            &GrpcEvent {
                                content: msg,
                                event_type: GrpcEventType::ClientMessage,
                                ..base_event.clone()
                            },
                            &UpdateSource::from_window_label(&window_label),
                        );
                    }
                    Err(error) => {
                        let _ = app_handle.db().upsert_grpc_event(
                            &GrpcEvent {
                                content: format!("Failed to send message: {}", error),
                                event_type: GrpcEventType::Error,
                                ..base_event.clone()
                            },
                            &UpdateSource::from_window_label(&window_label),
                        );
                    }
                }
            };

            let (maybe_stream, maybe_msg) =
                match (method_desc.is_client_streaming(), method_desc.is_server_streaming()) {
                    (true, true) => (
                        Some(
                            connection
                                .streaming(
                                    &service,
                                    &method,
                                    in_msg_stream,
                                    &metadata,
                                    client_cert.clone(),
                                    on_message.clone(),
                                )
                                .await,
                        ),
                        None,
                    ),
                    (true, false) => (
                        None,
                        Some(
                            connection
                                .client_streaming(
                                    &service,
                                    &method,
                                    in_msg_stream,
                                    &metadata,
                                    client_cert.clone(),
                                    on_message.clone(),
                                )
                                .await,
                        ),
                    ),
                    (false, true) => (
                        Some(connection.server_streaming(&service, &method, &msg, &metadata).await),
                        None,
                    ),
                    (false, false) => (
                        None,
                        Some(
                            connection
                                .unary(&service, &method, &msg, &metadata, client_cert.clone())
                                .await,
                        ),
                    ),
                };

            if !method_desc.is_client_streaming() {
                app_handle
                    .db()
                    .upsert_grpc_event(
                        &GrpcEvent {
                            event_type: GrpcEventType::ClientMessage,
                            content: msg,
                            ..base_event.clone()
                        },
                        &UpdateSource::from_window_label(window.label()),
                    )
                    .unwrap();
            }

            match maybe_msg {
                Some(Ok(msg)) => {
                    app_handle
                        .db()
                        .upsert_grpc_event(
                            &GrpcEvent {
                                metadata: metadata_to_map(msg.metadata().clone()),
                                content: if msg.metadata().len() == 0 {
                                    "Received response"
                                } else {
                                    "Received response with metadata"
                                }
                                .to_string(),
                                event_type: GrpcEventType::Info,
                                ..base_event.clone()
                            },
                            &UpdateSource::from_window_label(window.label()),
                        )
                        .unwrap();
                    let response_message = msg.into_inner();
                    let content = match connection
                        .serialize_message(&response_message, &metadata, client_cert.clone())
                        .await
                    {
                        Ok(content) => content,
                        Err(err) => {
                            app_handle
                                .db()
                                .upsert_grpc_event(
                                    &GrpcEvent {
                                        content: "Failed to read response".to_string(),
                                        error: Some(err.to_string()),
                                        status: Some(Code::Internal as i32),
                                        event_type: GrpcEventType::ConnectionEnd,
                                        ..base_event.clone()
                                    },
                                    &UpdateSource::from_window_label(window.label()),
                                )
                                .unwrap();
                            return;
                        }
                    };
                    app_handle
                        .db()
                        .upsert_grpc_event(
                            &GrpcEvent {
                                content,
                                event_type: GrpcEventType::ServerMessage,
                                ..base_event.clone()
                            },
                            &UpdateSource::from_window_label(window.label()),
                        )
                        .unwrap();
                    app_handle
                        .db()
                        .upsert_grpc_event(
                            &GrpcEvent {
                                content: "Connection complete".to_string(),
                                event_type: GrpcEventType::ConnectionEnd,
                                status: Some(Code::Ok as i32),
                                ..base_event.clone()
                            },
                            &UpdateSource::from_window_label(window.label()),
                        )
                        .unwrap();
                }
                Some(Err(yaak_grpc::error::Error::GrpcStreamError(e))) => {
                    app_handle
                        .db()
                        .upsert_grpc_event(
                            &(match e.status {
                                Some(s) => GrpcEvent {
                                    error: Some(s.message().to_string()),
                                    status: Some(s.code() as i32),
                                    content: "Request failed".to_string(),
                                    metadata: metadata_to_map(s.metadata().clone()),
                                    event_type: GrpcEventType::ConnectionEnd,
                                    ..base_event.clone()
                                },
                                None => GrpcEvent {
                                    error: Some(e.message),
                                    status: Some(Code::Unknown as i32),
                                    content: "Request failed".to_string(),
                                    event_type: GrpcEventType::ConnectionEnd,
                                    ..base_event.clone()
                                },
                            }),
                            &UpdateSource::from_window_label(window.label()),
                        )
                        .unwrap();
                }
                Some(Err(e)) => {
                    app_handle
                        .db()
                        .upsert_grpc_event(
                            &GrpcEvent {
                                error: Some(e.to_string()),
                                status: Some(Code::Unknown as i32),
                                content: "Request failed".to_string(),
                                event_type: GrpcEventType::ConnectionEnd,
                                ..base_event.clone()
                            },
                            &UpdateSource::from_window_label(window.label()),
                        )
                        .unwrap();
                }
                None => {
                    // Server streaming doesn't return the initial message
                }
            }

            let mut stream = match maybe_stream {
                Some(Ok(stream)) => {
                    app_handle
                        .db()
                        .upsert_grpc_event(
                            &GrpcEvent {
                                metadata: metadata_to_map(stream.metadata().clone()),
                                content: if stream.metadata().len() == 0 {
                                    "Received response"
                                } else {
                                    "Received response with metadata"
                                }
                                .to_string(),
                                event_type: GrpcEventType::Info,
                                ..base_event.clone()
                            },
                            &UpdateSource::from_window_label(window.label()),
                        )
                        .unwrap();
                    stream.into_inner()
                }
                Some(Err(yaak_grpc::error::Error::GrpcStreamError(e))) => {
                    warn!("GRPC stream error {e:?}");
                    app_handle
                        .db()
                        .upsert_grpc_event(
                            &(match e.status {
                                Some(s) => GrpcEvent {
                                    error: Some(s.message().to_string()),
                                    status: Some(s.code() as i32),
                                    content: "Stream failed".to_string(),
                                    metadata: metadata_to_map(s.metadata().clone()),
                                    event_type: GrpcEventType::ConnectionEnd,
                                    ..base_event.clone()
                                },
                                None => GrpcEvent {
                                    error: Some(e.message),
                                    status: Some(Code::Unknown as i32),
                                    content: "Stream failed".to_string(),
                                    event_type: GrpcEventType::ConnectionEnd,
                                    ..base_event.clone()
                                },
                            }),
                            &UpdateSource::from_window_label(window.label()),
                        )
                        .unwrap();
                    return;
                }
                Some(Err(e)) => {
                    app_handle
                        .db()
                        .upsert_grpc_event(
                            &GrpcEvent {
                                error: Some(e.to_string()),
                                status: Some(Code::Unknown as i32),
                                content: "Stream failed".to_string(),
                                event_type: GrpcEventType::ConnectionEnd,
                                ..base_event.clone()
                            },
                            &UpdateSource::from_window_label(window.label()),
                        )
                        .unwrap();
                    return;
                }
                None => return,
            };

            loop {
                match stream.message().await {
                    Ok(Some(msg)) => {
                        let message = match connection
                            .serialize_message(&msg, &metadata, client_cert.clone())
                            .await
                        {
                            Ok(message) => message,
                            Err(err) => {
                                app_handle
                                    .db()
                                    .upsert_grpc_event(
                                        &GrpcEvent {
                                            content: "Failed to read response".to_string(),
                                            error: Some(err.to_string()),
                                            status: Some(Code::Internal as i32),
                                            event_type: GrpcEventType::ConnectionEnd,
                                            ..base_event.clone()
                                        },
                                        &UpdateSource::from_window_label(window.label()),
                                    )
                                    .unwrap();
                                break;
                            }
                        };
                        app_handle
                            .db()
                            .upsert_grpc_event(
                                &GrpcEvent {
                                    content: message,
                                    event_type: GrpcEventType::ServerMessage,
                                    ..base_event.clone()
                                },
                                &UpdateSource::from_window_label(window.label()),
                            )
                            .unwrap();
                    }
                    Ok(None) => {
                        let trailers =
                            stream.trailers().await.unwrap_or_default().unwrap_or_default();
                        app_handle
                            .db()
                            .upsert_grpc_event(
                                &GrpcEvent {
                                    content: "Connection complete".to_string(),
                                    status: Some(Code::Ok as i32),
                                    metadata: metadata_to_map(trailers),
                                    event_type: GrpcEventType::ConnectionEnd,
                                    ..base_event.clone()
                                },
                                &UpdateSource::from_window_label(window.label()),
                            )
                            .unwrap();
                        break;
                    }
                    Err(status) => {
                        app_handle
                            .db()
                            .upsert_grpc_event(
                                &GrpcEvent {
                                    content: "Stream failed".to_string(),
                                    error: Some(status.message().to_string()),
                                    status: Some(status.code() as i32),
                                    metadata: metadata_to_map(status.metadata().clone()),
                                    event_type: GrpcEventType::ConnectionEnd,
                                    ..base_event.clone()
                                },
                                &UpdateSource::from_window_label(window.label()),
                            )
                            .unwrap();
                        break;
                    }
                }
            }
        }
    };

    {
        let conn_id = conn_id.clone();
        tauri::async_runtime::spawn(async move {
            let w = app_handle.clone();
            tokio::select! {
                _ = grpc_listen => {
                    let events = w.db().list_grpc_events(&conn_id).unwrap();
                    let closed_event = events
                        .iter()
                        .find(|e| GrpcEventType::ConnectionEnd == e.event_type);
                    let closed_status = closed_event.and_then(|e| e.status).unwrap_or(Code::Unavailable as i32);
                    w.with_tx(|c| {
                        c.upsert_grpc_connection(
                            &GrpcConnection{
                                elapsed: start.elapsed().as_millis() as i32,
                                status: closed_status,
                                state: GrpcConnectionState::Closed,
                                ..c.get_grpc_connection( &conn_id).unwrap().clone()
                            },
                            &UpdateSource::from_window_label(window.label()),
                        )
                    }).unwrap();
                },
                _ = cancelled_rx.changed() => {
                    w.db().upsert_grpc_event(
                        &GrpcEvent {
                            content: "Cancelled".to_string(),
                            event_type: GrpcEventType::ConnectionEnd,
                            status: Some(Code::Cancelled as i32),
                            ..base_msg.clone()
                        },
                        &UpdateSource::from_window_label(window.label()),
                    ).unwrap();
                    w.with_tx(|c| {
                        c.upsert_grpc_connection(
                            &GrpcConnection{
                            elapsed: start.elapsed().as_millis() as i32,
                            status: Code::Cancelled as i32,
                            state: GrpcConnectionState::Closed,
                                ..c.get_grpc_connection( &conn_id).unwrap().clone()
                            },
                            &UpdateSource::from_window_label(window.label()),
                        )
                    }).unwrap();
                },
            }
            w.unlisten(event_handler);
        });
    };

    Ok(conn.id)
}

async fn cmd_restart<R: Runtime>(app_handle: AppHandle<R>) -> YaakResult<()> {
    restart::request_restart(&app_handle);
    Ok(())
}

/// Send without saving anything.
///
/// The response never reaches the database, so its body cannot be read back by
/// id later the way a saved response's can. It comes back here instead, which
/// is the only copy the caller gets.
async fn cmd_send_ephemeral_request<R: Runtime>(
    mut request: HttpRequest,
    environment_id: Option<&str>,
    cookie_jar_id: Option<&str>,
    window: WebviewWindow<R>,
    app_handle: AppHandle<R>,
) -> YaakResult<EphemeralHttpResponse> {
    let response = HttpResponse::default();
    request.id = "".to_string();
    let environment = match environment_id {
        Some(id) => Some(app_handle.db().get_environment(id)?),
        None => None,
    };
    let cookie_jar = match cookie_jar_id {
        Some(id) => Some(app_handle.db().get_cookie_jar(id)?),
        None => None,
    };

    let (cancel_tx, mut cancel_rx) = tokio::sync::watch::channel(false);
    window.listen_any(format!("cancel_http_response_{}", response.id), move |_event| {
        if let Err(e) = cancel_tx.send(true) {
            warn!("Failed to send cancel event for ephemeral request {e:?}");
        }
    });

    let sent =
        send_http_request(&window, &request, &response, environment, cookie_jar, &mut cancel_rx)
            .await?;

    // Blanking the request id above is what makes this send unsaved, so the
    // engine always hands the body back. Failing loudly beats returning an
    // empty body that reads as "the server sent nothing".
    let ResponseBody::Returned(body) = sent.body else {
        return Err(GenericError("Unsaved response did not return a body".to_string()));
    };

    Ok(EphemeralHttpResponse { response: sent.response, body })
}

async fn cmd_format_graphql(text: &str) -> YaakResult<String> {
    match pretty_graphql::format_text(text, &Default::default()) {
        Ok(formatted) => Ok(formatted),
        Err(_) => Ok(text.to_string()),
    }
}

async fn cmd_http_response_body<R: Runtime>(
    window: WebviewWindow<R>,
    plugin_manager: State<'_, PluginManager>,
    response_id: &str,
    filter: Option<&str>,
) -> YaakResult<FilterResponse> {
    let location = locate_response_body(&window.db(), response_id)?;
    let Some(body_path) = location.path else {
        return Ok(FilterResponse { content: String::new(), error: None });
    };

    let content_type = location.content_type.as_str();
    let body = read_response_body(&body_path, content_type)
        .await
        .ok_or(GenericError("Failed to find response body".to_string()))?;

    match filter {
        Some(filter) if !filter.is_empty() => Ok(plugin_manager
            .filter_data(&window.plugin_context(), filter, &body, content_type)
            .await?),
        _ => Ok(FilterResponse { content: body, error: None }),
    }
}

async fn cmd_get_sse_events<R: Runtime>(
    app_handle: AppHandle<R>,
    response_id: &str,
) -> YaakResult<Vec<ServerSentEvent>> {
    let Some(body_path) = locate_response_body(&app_handle.db(), response_id)?.path else {
        return Ok(Vec::new());
    };

    let body = fs::read(body_path)?;
    let mut event_parser = EventParser::new();
    event_parser.process_bytes(body.into())?;

    let mut events = Vec::new();
    while let Some(e) = event_parser.get_event() {
        if let SSE::Event(e) = e {
            events.push(ServerSentEvent {
                event_type: e.event_type,
                data: e.data,
                id: e.id,
                retry: e.retry,
            });
        }
    }

    Ok(events)
}

async fn cmd_import_data<R: Runtime>(
    window: WebviewWindow<R>,
    file_path: &str,
) -> YaakResult<BatchUpsertResult> {
    import_data(&window, file_path).await
}

async fn cmd_import_url<R: Runtime>(
    window: WebviewWindow<R>,
    url: &str,
) -> YaakResult<BatchUpsertResult> {
    import_url(&window, url).await
}















/// Decodes base64 and writes the bytes to a file the user picked.
///
/// The webview can't do this itself: its `fs` permissions are read-only and scoped to the app
/// data directory, and widening them so it could write anywhere would be a poor trade in an app
/// whose whole job is rendering responses from servers it doesn't control.
///
/// Base64 in rather than bytes for two reasons. A `Vec<u8>` crosses the IPC boundary as a JSON
/// array of numbers, several times the size of the thing being saved. And the callers that need
/// this — values the editor collapsed — are holding base64 already, so passing it through
/// untouched means the save never decodes megabytes on the main thread.
async fn cmd_save_base64_to_binary<R: Runtime>(
    _app_handle: AppHandle<R>,
    filepath: &str,
    data: &str,
) -> YaakResult<()> {
    use base64::Engine;
    let bytes = base64::engine::general_purpose::STANDARD
        .decode(data)
        .map_err(|e| GenericError(format!("Data is not valid base64: {e}")))?;
    fs::write(filepath, bytes).map_err(|e| GenericError(e.to_string()))?;
    Ok(())
}

async fn cmd_send_http_request<R: Runtime>(
    app_handle: AppHandle<R>,
    window: WebviewWindow<R>,
    environment_id: Option<&str>,
    cookie_jar_id: Option<&str>,
    request_id: String,
) -> YaakResult<HttpResponse> {
    let request = app_handle.db().get_http_request(&request_id)?;

    let blobs = app_handle.blob_manager();
    let response = app_handle.db().upsert_http_response(
        &HttpResponse {
            request_id: request.id.clone(),
            workspace_id: request.workspace_id.clone(),
            ..Default::default()
        },
        &UpdateSource::from_window_label(window.label()),
        &blobs,
    )?;

    let (cancel_tx, mut cancel_rx) = tokio::sync::watch::channel(false);
    app_handle.listen_any(format!("cancel_http_response_{}", response.id), move |_event| {
        if let Err(e) = cancel_tx.send(true) {
            warn!("Failed to send cancel event for request {e:?}");
        }
    });

    let environment = match environment_id {
        Some(id) => match app_handle.db().get_environment(id) {
            Ok(env) => Some(env),
            Err(e) => {
                warn!("Failed to find environment by id {id} {}", e);
                None
            }
        },
        None => None,
    };

    let cookie_jar = match cookie_jar_id {
        Some(id) => Some(app_handle.db().get_cookie_jar(id)?),
        None => None,
    };

    let r = match send_http_request(
        &window,
        &request,
        &response,
        environment,
        cookie_jar,
        &mut cancel_rx,
    )
    .await
    {
        Ok(sent) => sent.response,
        Err(e) => {
            let resp = app_handle.db().get_http_response(&response.id)?;
            app_handle.db().upsert_http_response(
                &HttpResponse {
                    state: HttpResponseState::Closed,
                    error: Some(e.to_string()),
                    ..resp
                },
                &UpdateSource::from_window_label(window.label()),
                &blobs,
            )?
        }
    };

    Ok(r)
}


async fn cmd_new_child_window<R: Runtime>(
    parent_window: WebviewWindow<R>,
    url: &str,
    label: &str,
    title: &str,
    inner_size: (f64, f64),
) -> YaakResult<()> {
    let use_native_titlebar = parent_window.app_handle().db().get_settings().use_native_titlebar;
    let initialization_script = initial_appearance_script(&parent_window.app_handle());
    let win = yaak_window::window::create_child_window(
        &parent_window,
        url,
        label,
        title,
        inner_size,
        initialization_script,
        use_native_titlebar,
    )?;
    setup_window_menu(&win)?;
    Ok(())
}

async fn cmd_new_main_window<R: Runtime>(app_handle: AppHandle<R>, url: &str) -> YaakResult<()> {
    let use_native_titlebar = app_handle.db().get_settings().use_native_titlebar;
    let initialization_script = initial_appearance_script(&app_handle);
    let win = yaak_window::window::create_main_window(
        &app_handle,
        url,
        initialization_script,
        use_native_titlebar,
    )?;
    setup_window_menu(&win)?;
    Ok(())
}

async fn cmd_check_for_updates<R: Runtime>(
    window: WebviewWindow<R>,
    yaak_updater: State<'_, Mutex<YaakUpdater>>,
) -> YaakResult<bool> {
    let update_mode = get_update_mode(&window).await?;
    let settings = window.db().get_settings();
    Ok(yaak_updater
        .lock()
        .await
        .check_now(&window, update_mode, settings.auto_download_updates, UpdateTrigger::User)
        .await?)
}

#[cfg_attr(mobile, tauri::mobile_entry_point)]
#[cfg_attr(feature = "cef", tauri::cef_entry_point)]
pub fn run() {
    // GUI apps launched via Finder/launchd inherit a 256 open-file soft limit on macOS
    // (1024 on most Linux desktops). SQLite WAL connections hold ~3 fds each, so raise
    // the limit toward the hard cap before opening any DB pools.
    #[cfg(any(target_os = "macos", target_os = "linux"))]
    if let Err(e) = rlimit::increase_nofile_limit(10240) {
        eprintln!("Failed to raise open-file limit: {e}");
    }

    let mut builder = tauri::Builder::<TauriRuntime>::default().plugin(
        Builder::default()
            .targets([
                Target::new(TargetKind::Stdout),
                Target::new(TargetKind::LogDir { file_name: None }),
                Target::new(TargetKind::Webview),
            ])
            .level_for("plugin_runtime", log::LevelFilter::Info)
            .level_for("cookie_store", log::LevelFilter::Info)
            .level_for("eventsource_client::event_parser", log::LevelFilter::Info)
            .level_for("h2", log::LevelFilter::Info)
            .level_for("hyper", log::LevelFilter::Info)
            .level_for("hyper_util", log::LevelFilter::Info)
            .level_for("hyper_rustls", log::LevelFilter::Info)
            .level_for("reqwest", log::LevelFilter::Info)
            .level_for("sqlx", log::LevelFilter::Debug)
            .level_for("tao", log::LevelFilter::Info)
            .level_for("tokio_util", log::LevelFilter::Info)
            .level_for("tonic", log::LevelFilter::Info)
            .level_for("tower", log::LevelFilter::Info)
            .level_for("tracing", log::LevelFilter::Warn)
            .level_for("swc_ecma_codegen", log::LevelFilter::Off)
            .level_for("swc_ecma_transforms_base", log::LevelFilter::Off)
            .with_colors(ColoredLevelConfig::default())
            .level(if is_dev() { log::LevelFilter::Debug } else { log::LevelFilter::Info })
            .build(),
    );

    // Only enable single-instance in production builds. In dev mode, we want to allow
    // multiple instances for testing and worktree workflows (running multiple branches).
    if !is_dev() {
        builder = builder.plugin(tauri_plugin_single_instance::init(|app, _args, _cwd| {
            // When trying to open a new app instance (common operation on Linux),
            // focus the first existing window we find instead of opening a new one
            // TODO: Keep track of the last focused window and always focus that one
            if let Some(window) = app.webview_windows().values().next() {
                let _ = window.set_focus();
            }
        }));
    }

    builder = builder
        .plugin(tauri_plugin_clipboard_manager::init())
        .plugin(tauri_plugin_opener::init())
        .plugin(tauri_plugin_deep_link::init())
        .plugin(tauri_plugin_shell::init())
        .plugin(tauri_plugin_dialog::init())
        .plugin(tauri_plugin_os::init())
        .plugin(tauri_plugin_fs::init())
        .plugin(yaak_mac_window::init())
        .plugin(models_ext::init()) // Database setup only. Must be before plugins_ext which depends on db
        .plugin(plugins_ext::init())
        .plugin(yaak_fonts::init());

    #[cfg(feature = "license")]
    {
        builder = builder.plugin(yaak_license::init());
    }

    #[cfg(feature = "updater")]
    {
        builder = builder.plugin(tauri_plugin_updater::Builder::default().build());
    }

    builder
        .setup(|app| {
            let lifecycle_host = yaak_lifecycle::Host::owner()
                .with_responses_dir(app.path().app_data_dir()?.join("responses"));
            if let Err(e) =
                yaak_lifecycle::on_launch(&lifecycle_host, &app.db(), &app.blob_manager())
            {
                error!("on_launch hook failed: {e:?}");
            }

            // The RPC command registry — every frontend command dispatches
            // through this via the single `rpc` Tauri command
            app.manage(rpc_ext::build_rpc_router::<TauriRuntime>());

            // Initialize HTTP connection manager
            app.manage(yaak_http::manager::HttpConnectionManager::new());

            // Initialize encryption manager
            let query_manager =
                app.state::<yaak_models::query_manager::QueryManager>().inner().clone();
            let app_id = app.config().identifier.to_string();
            app.manage(yaak_crypto::manager::EncryptionManager::new(query_manager, app_id));
            #[cfg(any(target_os = "linux", target_os = "macos"))]
            if let Some(state) = yaak_system_appearance::watch(app.app_handle().clone()) {
                app.manage(state);
            }

            {
                let app_handle = app.app_handle().clone();
                app.deep_link().on_open_url(move |event| {
                    info!("Handling deep link open");
                    let app_handle = app_handle.clone();
                    tauri::async_runtime::spawn(async move {
                        for url in event.urls() {
                            if let Err(e) = handle_deep_link(&app_handle, &url).await {
                                warn!("Failed to handle deep link {}: {e:?}", url.to_string());
                                let _ = app_handle.emit(
                                    "show_toast",
                                    ShowToastRequest {
                                        message: format!(
                                            "Error handling deep link: {}",
                                            e.to_string()
                                        ),
                                        color: Some(Color::Danger),
                                        icon: None,
                                        timeout: None,
                                    },
                                );
                            };
                        }
                    });
                });
            };

            // Add updater
            let yaak_updater = YaakUpdater::new();
            app.manage(Mutex::new(yaak_updater));

            // Add notifier
            let yaak_notifier = YaakNotifier::new();
            app.manage(Mutex::new(yaak_notifier));

            // Add GRPC manager
            let protoc_include_dir = app
                .path()
                .resolve("vendored/protoc/include", BaseDirectory::Resource)
                .expect("failed to resolve protoc include directory");
            let protoc_bin_name = if cfg!(windows) { "yaakprotoc.exe" } else { "yaakprotoc" };
            let protoc_bin_path = app
                .path()
                .resolve(format!("vendored/protoc/{}", protoc_bin_name), BaseDirectory::Resource)
                .expect("failed to resolve yaakprotoc binary");
            let grpc_config = GrpcConfig { protoc_include_dir, protoc_bin_path };
            let grpc_handle = GrpcHandle::new(grpc_config);
            app.manage(Mutex::new(grpc_handle));

            // Add WebSocket manager
            let ws_manager = yaak_ws::WebsocketManager::new();
            app.manage(Mutex::new(ws_manager));

            // Specific settings
            let settings = app.db().get_settings();
            app.app_handle().set_native_titlebar(settings.use_native_titlebar);

            monitor_plugin_events(&app.app_handle().clone());

            Ok(())
        })
        .invoke_handler(tauri::generate_handler![rpc_ext::rpc])
        .build(tauri::generate_context!())
        .expect("error while running tauri application")
        .run(|app_handle, event| {
            match event {
                RunEvent::Ready => {
                    let use_native_titlebar = app_handle.db().get_settings().use_native_titlebar;
                    let initialization_script = initial_appearance_script(app_handle);
                    if let Ok(win) = yaak_window::window::create_main_window(
                        app_handle,
                        "/",
                        initialization_script,
                        use_native_titlebar,
                    ) {
                        let _ = setup_window_menu(&win);
                    }
                    let h = app_handle.clone();
                    tauri::async_runtime::spawn(async move {
                        let info = history::get_or_upsert_launch_info(&h);
                        debug!("Launched Yaak {:?}", info);
                    });
                }
                RunEvent::WindowEvent { event: WindowEvent::ThemeChanged(_), .. } => {
                    // On macOS this is how OS appearance changes arrive: tao observes
                    // AppleInterfaceThemeChangedNotification and emits it for every window
                    #[cfg(any(target_os = "linux", target_os = "macos"))]
                    if let Some(state) =
                        app_handle.try_state::<yaak_system_appearance::SystemAppearanceState>()
                    {
                        yaak_system_appearance::emit_change(app_handle, &state);
                    }
                }
                RunEvent::WindowEvent { event: WindowEvent::Focused(true), label, .. } => {
                    #[cfg(any(target_os = "linux", target_os = "macos"))]
                    if let Some(state) =
                        app_handle.try_state::<yaak_system_appearance::SystemAppearanceState>()
                    {
                        yaak_system_appearance::emit_change(app_handle, &state);
                    }

                    if cfg!(feature = "updater") {
                        // Run update check whenever the window is focused
                        let w = app_handle.get_webview_window(&label).unwrap();
                        let h = app_handle.clone();
                        tauri::async_runtime::spawn(async move {
                            let settings = w.db().get_settings();
                            if settings.autoupdate {
                                time::sleep(Duration::from_secs(3)).await; // Wait a bit so it's not so jarring
                                let val: State<'_, Mutex<YaakUpdater>> = h.state();
                                let update_mode = get_update_mode(&w).await.unwrap();
                                if let Err(e) = val
                                    .lock()
                                    .await
                                    .maybe_check(&w, settings.auto_download_updates, update_mode)
                                    .await
                                {
                                    warn!("Failed to check for updates {e:?}");
                                }
                            };
                        });
                    }

                    let h = app_handle.clone();
                    tauri::async_runtime::spawn(async move {
                        let windows = h.webview_windows();
                        let w = windows.values().next().unwrap();
                        tokio::time::sleep(Duration::from_millis(4000)).await;
                        let val: State<'_, Mutex<YaakNotifier>> = w.state();
                        let mut n = val.lock().await;
                        if let Err(e) = n.maybe_check(&w).await {
                            warn!("Failed to check for notifications {}", e)
                        }
                    });
                }
                RunEvent::Exit => restart::relaunch_if_requested(),
                _ => {}
            };
        });
}

async fn get_update_mode<R: Runtime>(window: &WebviewWindow<R>) -> YaakResult<UpdateMode> {
    let settings = window.db().get_settings();
    Ok(UpdateMode::new(settings.update_channel.as_str()))
}

fn safe_uri(endpoint: &str) -> String {
    if endpoint.starts_with("http://") || endpoint.starts_with("https://") {
        endpoint.into()
    } else {
        format!("http://{}", endpoint)
    }
}

fn monitor_plugin_events<R: Runtime>(app_handle: &AppHandle<R>) {
    let app_handle = app_handle.clone();
    tauri::async_runtime::spawn(async move {
        let plugin_manager: State<'_, PluginManager> = app_handle.state();
        let (rx_id, mut rx) = plugin_manager.subscribe("app").await;

        while let Some(event) = rx.recv().await {
            let app_handle = app_handle.clone();
            let plugin =
                match plugin_manager.get_plugin_by_ref_id(event.plugin_ref_id.as_str()).await {
                    None => {
                        warn!("Failed to get plugin for event {:?}", event);
                        continue;
                    }
                    Some(p) => p,
                };

            // We might have recursive back-and-forth calls between app and plugin, so we don't
            // want to block here
            tauri::async_runtime::spawn(async move {
                let ev = plugin_events::handle_plugin_event(&app_handle, &event, &plugin).await;

                let ev = match ev {
                    Ok(Some(ev)) => ev,
                    // Nothing to say, or the reply comes later from somewhere else.
                    Ok(None) => return,
                    Err(e) => {
                        warn!("Failed to handle plugin event: {e:?}");
                        let _ = app_handle.emit(
                            "show_toast",
                            InternalEventPayload::ShowToastRequest(ShowToastRequest {
                                message: e.to_string(),
                                color: Some(Color::Danger),
                                icon: None,
                                timeout: Some(30000),
                            }),
                        );
                        // Tell the plugin as well as the user. It is awaiting a
                        // reply, and a toast it cannot see would leave it
                        // waiting for one that never comes.
                        InternalEventPayload::ErrorResponse(ErrorResponse { error: e.to_string() })
                    }
                };

                let plugin_manager: State<'_, PluginManager> = app_handle.state();
                if let Err(e) = plugin_manager.reply(&event, &ev).await {
                    warn!("Failed to reply to plugin manager: {:?}", e)
                }
            });
        }
        plugin_manager.unsubscribe(rx_id.as_str()).await;
    });
}

async fn call_frontend<R: Runtime>(
    window: &WebviewWindow<R>,
    event: &InternalEvent,
) -> Option<InternalEventPayload> {
    window.emit_to(window.label(), "plugin_event", event.clone()).unwrap();
    let (tx, mut rx) = tokio::sync::watch::channel(None);

    let reply_id = event.id.clone();
    let event_id = window.clone().listen(reply_id, move |ev| {
        let resp: InternalEvent = serde_json::from_str(ev.payload()).unwrap();
        if let Err(e) = tx.send(Some(resp.payload)) {
            warn!("Failed to prompt for text {e:?}");
        }
    });

    // When reply shows up, unlisten to events and return
    if let Err(e) = rx.changed().await {
        warn!("Failed to check channel changed {e:?}");
    }
    window.unlisten(event_id);

    let v = rx.borrow();
    v.to_owned()
}

fn get_window_from_plugin_context<R: Runtime>(
    app_handle: &AppHandle<R>,
    plugin_context: &PluginContext,
) -> Result<WebviewWindow<R>> {
    let label = match &plugin_context.label {
        Some(label) => label,
        None => {
            return app_handle
                .webview_windows()
                .iter()
                .next()
                .map(|(_, w)| w.to_owned())
                .ok_or(GenericError("No windows open".to_string()));
        }
    };

    let window = app_handle
        .webview_windows()
        .iter()
        .find_map(|(_, w)| if w.label() == label { Some(w.to_owned()) } else { None });

    if window.is_none() {
        error!("Failed to find window by {plugin_context:?}");
    }

    Ok(window.ok_or(GenericError(format!("Failed to find window for {}", label)))?)
}

fn workspace_from_window<R: Runtime>(window: &WebviewWindow<R>) -> Option<Workspace> {
    window.workspace_id().and_then(|id| window.db().get_workspace(&id).ok())
}

fn environment_from_window<R: Runtime>(window: &WebviewWindow<R>) -> Option<Environment> {
    window.environment_id().and_then(|id| window.db().get_environment(&id).ok())
}

fn cookie_jar_from_window<R: Runtime>(window: &WebviewWindow<R>) -> Option<CookieJar> {
    window.cookie_jar_id().and_then(|id| window.db().get_cookie_jar(&id).ok())
}
