#[cfg(not(coverage))]
#[allow(clippy::too_many_arguments)]
fn run_preview_feed(
    server_addr: Arc<Mutex<String>>,
    monitor_id: u32,
    profile: PreviewProfile,
    session_active: Arc<AtomicBool>,
    active_bindings: Arc<AtomicUsize>,
    running: Arc<AtomicBool>,
    shared: Arc<Mutex<SharedPreviewState>>,
    log_sink: Arc<Mutex<Option<std::sync::mpsc::Sender<String>>>>,
) -> Result<()> {
    let mut startup_error = None;
    let mut selected = None;
    for decoder_name in preview_decoder_candidates() {
        match build_preview_pipeline(profile, &decoder_name) {
            Ok((pipeline, appsrc, appsink, decoder_label)) => {
                match pipeline
                    .set_state(gst::State::Playing)
                    .context("starting launcher preview pipeline")
                {
                    Ok(_) => {
                        selected = Some((pipeline, appsrc, appsink, decoder_label));
                        break;
                    }
                    Err(err) => {
                        let _ = pipeline.set_state(gst::State::Null);
                        startup_error = Some(err);
                    }
                }
            }
            Err(err) => {
                startup_error = Some(err);
            }
        }
    }
    let (pipeline, appsrc, appsink, decoder_name) = selected.ok_or_else(|| {
        startup_error.unwrap_or_else(|| anyhow::anyhow!("no usable H.264 decoder"))
    })?;
    let parser = pipeline.by_name("preview_parse");
    let decoder = pipeline.by_name("decoder");
    if let Ok(mut slot) = shared.lock() {
        slot.telemetry.note_decoder(&decoder_name);
    }
    {
        let shared = Arc::clone(&shared);
        pipeline.connect_deep_element_added(move |_, _, element| {
            if let Some(decoder_label) = preview_decoder_label(element)
                && let Ok(mut slot) = shared.lock()
            {
                slot.telemetry.note_decoder(&decoder_label);
            }
        });
    }
    let sample_worker = {
        let shared = Arc::clone(&shared);
        let appsink = appsink.clone();
        let parser = parser.clone();
        let decoder = decoder.clone();
        let running = Arc::clone(&running);
        std::thread::spawn(move || {
            loop {
                if !running.load(Ordering::Relaxed) {
                    break;
                }
                if let Some(sample) = appsink.try_pull_sample(gst::ClockTime::from_mseconds(250)) {
                    if let Some(parser) = parser.as_ref() {
                        record_preview_caps(&shared, parser, "src", PreviewCapsKind::Stream);
                    }
                    if let Some(decoder) = decoder.as_ref() {
                        record_preview_caps(&shared, decoder, "src", PreviewCapsKind::Decoded);
                    }
                    if let Some(caps) = sample.caps() {
                        let caps_label = preview_caps_summary(&caps);
                        if !caps_label.is_empty()
                            && let Ok(mut slot) = shared.lock()
                        {
                            slot.telemetry.note_rendered_caps(&caps_label);
                        }
                    }
                    if let Some(frame) = sample_to_frame(&sample)
                        && let Ok(mut slot) = shared.lock()
                    {
                        slot.push_frame(frame);
                    }
                }
            }
        })
    };

    let rt = tokio::runtime::Builder::new_current_thread()
        .enable_all()
        .build()
        .context("building preview tokio runtime")?;

    let running_for_loop = Arc::clone(&running);
    let _ = rt.block_on(async move {
        let mut was_active = false;
        let mut retry_delay = Duration::from_millis(750);
        loop {
            if !running_for_loop.load(Ordering::Relaxed) {
                break;
            }
            let active_now =
                session_active.load(Ordering::Relaxed) && active_bindings.load(Ordering::Relaxed) > 0;
            if !active_now {
                was_active = false;
                retry_delay = Duration::from_millis(750);
                set_shared_status(&shared, &log_sink, monitor_id, PREVIEW_IDLE_STATUS, true);
                tokio::time::sleep(Duration::from_millis(150)).await;
                continue;
            }

            if !was_active {
                was_active = true;
                set_shared_status(
                    &shared,
                    &log_sink,
                    monitor_id,
                    "Waking relay preview...",
                    true,
                );
                tokio::time::sleep(Duration::from_millis(350)).await;
            }

            set_shared_status(
                &shared,
                &log_sink,
                monitor_id,
                "Connecting relay preview...",
                true,
            );
            let current_addr = match server_addr.lock() {
                Ok(value) => value.clone(),
                Err(_) => {
                    set_shared_status(
                        &shared,
                        &log_sink,
                        monitor_id,
                        "Preview address is unavailable.",
                        true,
                    );
                    tokio::time::sleep(Duration::from_millis(750)).await;
                    continue;
                }
            };

            let channel = match crate::relay_transport::endpoint(&current_addr) {
                Ok(endpoint) => match endpoint.tcp_nodelay(true).connect().await {
                    Ok(channel) => channel,
                    Err(err) => {
                        warn!(monitor_id, ?err, "launcher preview connect failed");
                        log_preview_issue(
                            &shared,
                            &log_sink,
                            monitor_id,
                            &format!("Preview host is unavailable: {err}"),
                        );
                        set_shared_status(
                            &shared,
                            &log_sink,
                            monitor_id,
                            "Preview host is unavailable.",
                            true,
                        );
                        tokio::time::sleep(retry_delay).await;
                        continue;
                    }
                },
                Err(err) => {
                    warn!(monitor_id, ?err, "launcher preview endpoint invalid");
                    log_preview_issue(
                        &shared,
                        &log_sink,
                        monitor_id,
                        &format!("Preview address is invalid: {err}"),
                    );
                    set_shared_status(
                        &shared,
                        &log_sink,
                        monitor_id,
                        "Preview address is invalid.",
                        true,
                    );
                    tokio::time::sleep(retry_delay).await;
                    continue;
                }
            };

            let mut cli = RelayClient::new(channel);
            let req = MonitorRequest {
                id: monitor_id,
                max_bitrate: profile.max_bitrate_kbit,
                requested_width: profile.requested_width.max(0) as u32,
                requested_height: profile.requested_height.max(0) as u32,
                requested_fps: profile.requested_fps,
                source_id: Some(profile.source_monitor_id),
            };
            match cli.capture_video(Request::new(req)).await {
                Ok(mut stream) => {
                    retry_delay = Duration::from_millis(750);
                    debug!(monitor_id, "launcher preview connected");
                    set_shared_status(
                        &shared,
                        &log_sink,
                        monitor_id,
                        "Waiting for stream...",
                        true,
                    );
                    loop {
                        if !session_active.load(Ordering::Relaxed)
                            || !running_for_loop.load(Ordering::Relaxed)
                            || active_bindings.load(Ordering::Relaxed) == 0
                        {
                            break;
                        }
                        match tokio::time::timeout(
                            Duration::from_millis(300),
                            stream.get_mut().message(),
                        )
                        .await
                        {
                            Ok(Ok(Some(pkt))) => {
                                record_preview_packet(&shared, &pkt);
                                push_preview_packet(&appsrc, pkt);
                            }
                            Ok(Ok(None)) => {
                                set_shared_status(
                                    &shared,
                                    &log_sink,
                                    monitor_id,
                                    "Preview stream ended.",
                                    true,
                                );
                                retry_delay = Duration::from_millis(1_500);
                                break;
                            }
                            Ok(Err(err)) => {
                                warn!(monitor_id, ?err, "launcher preview stream error");
                                log_preview_issue(
                                    &shared,
                                    &log_sink,
                                    monitor_id,
                                    &format!("Preview stream error: {err}"),
                                );
                                set_shared_status(
                                    &shared,
                                    &log_sink,
                                    monitor_id,
                                    "Preview stream error. See session log.",
                                    true,
                                );
                                retry_delay =
                                    preview_retry_delay(retry_delay, Some(&err.to_string()));
                                break;
                            }
                            Err(_) => continue,
                        }
                    }
                }
                Err(err) => {
                    if preview_startup_condition(&err) {
                        debug!(
                            monitor_id,
                            ?err,
                            "launcher preview waiting for capture pipeline"
                        );
                        log_preview_issue(
                            &shared,
                            &log_sink,
                            monitor_id,
                            &format!("Waiting for capture pipeline: {err}"),
                        );
                        set_shared_status(
                            &shared,
                            &log_sink,
                            monitor_id,
                            "Waiting for capture pipeline...",
                            true,
                        );
                        retry_delay = preview_retry_delay(retry_delay, Some(err.message()));
                    } else {
                        warn!(monitor_id, ?err, "launcher preview rpc failed");
                        log_preview_issue(
                            &shared,
                            &log_sink,
                            monitor_id,
                            &format!("Preview RPC failed: {err}"),
                        );
                        set_shared_status(
                            &shared,
                            &log_sink,
                            monitor_id,
                            "Preview RPC failed. See session log.",
                            true,
                        );
                        retry_delay = preview_retry_delay(retry_delay, Some(err.message()));
                    }
                }
            }
            tokio::time::sleep(retry_delay).await;
        }
        #[allow(unreachable_code)]
        Ok::<(), anyhow::Error>(())
    });

    let _ = pipeline.set_state(gst::State::Null);
    running.store(false, Ordering::Relaxed);
    let _ = sample_worker.join();

    Ok(())
}
