use kithara_platform::thread::assert_main_thread;

use crate::impls::session;

/// Ensure the main-thread session client exists in `Local` mode.
///
/// Must be called on the main thread **before** [`init_worker_session`]
/// so that the main thread gets a `Local` session and Workers get `Remote`.
pub fn ensure_main_session() {
    assert_main_thread("ensure_main_session");
    session::session_client();
}

/// Initialise the Worker ↔ main-thread session channel.
///
/// Must be called **once** on the main thread **before** any Worker
/// calls [`PlayerImpl::new`](crate::PlayerImpl::new).
pub fn init_worker_session() {
    assert_main_thread("init_worker_session");
    session::init_worker_channel();
}

/// Pre-initialise the audio context and AudioWorklet eagerly.
///
/// Call on the main thread **after** [`ensure_main_session`] and
/// [`init_worker_session`]. This creates the AudioContext in suspended
/// state and starts the async AudioWorklet module load. Once complete,
/// `firewheel-web-audio` registers auto-resume listeners so that the
/// very first user click resumes the context.
pub fn warm_up_audio() {
    assert_main_thread("warm_up_audio");
    session::warm_up_audio();
}

/// Poll pending session commands from Workers and update the audio graph.
///
/// Call this on the main thread from `requestAnimationFrame`.
pub fn tick_and_poll() {
    assert_main_thread("tick_and_poll");
    session::tick_and_poll_remote();
}

/// Current playback position in seconds (read from shared atomics).
pub fn bridge_position_secs() -> f64 {
    session::bridge_position_secs()
}

/// Current media duration in seconds (read from shared atomics).
pub fn bridge_duration_secs() -> f64 {
    session::bridge_duration_secs()
}

/// Whether playback is active (read from shared atomics).
pub fn bridge_is_playing() -> bool {
    session::bridge_is_playing()
}

/// Audio-thread process count (read from shared atomics).
pub fn bridge_process_count() -> u64 {
    session::bridge_process_count()
}
