//! Process-wide tokio runtime, initialized lazily on first use.
//!
//! NEVER initialize at import/module-load time: spawning runtime threads
//! before an application forks (common in Python preload patterns) leaves
//! the child with a dead runtime. Lazy init means a child that never
//! touched the SDK pre-fork gets a fresh runtime on first use.

use std::future::Future;
use std::sync::OnceLock;

use tokio::runtime::Runtime;

static RUNTIME: OnceLock<Runtime> = OnceLock::new();

/// Return the process-wide multi-threaded tokio runtime, building it on first
/// call. Safe to call after a fork in a child that never used the SDK pre-fork.
pub fn runtime() -> &'static Runtime {
    RUNTIME.get_or_init(|| {
        tokio::runtime::Builder::new_multi_thread()
            // The SDK is a thin RPC client; two workers cover concurrent
            // exec/wait/cancel without burning idle threads in every
            // Python process that imports sail.
            .worker_threads(2)
            .thread_name("sail-core")
            .enable_all()
            .build()
            .expect("failed to build sail-core tokio runtime")
    })
}

/// Drive an SDK future to completion on the shared internal runtime, for
/// synchronous callers outside any async context.
///
/// Must not be called from within a tokio runtime ("Cannot start a runtime
/// from within a runtime"); an async host should await the `async` API
/// directly instead.
// The sync facade for the PyO3 bridge (with the GIL released) and the CLI. The
// debug assert documents the never-inside-a-runtime invariant of those entry
// points.
pub fn block_on<F: Future>(future: F) -> F::Output {
    debug_assert!(
        tokio::runtime::Handle::try_current().is_err(),
        "sail::block_on called from within a tokio runtime; use the async API instead"
    );
    runtime().block_on(future)
}
