impl SnapshotReport {
    pub fn to_pretty_json(&self) -> Result<String, serde_json::Error> {
        serde_json::to_string_pretty(self)
    }

    pub fn to_pretty_text(&self) -> String {
        let mut text = String::new();
        let server_version = self.server_version.as_deref().unwrap_or("unknown");
        let server_state = if self.server_available {
            "reachable"
        } else {
            "unreachable"
        };
        let _ = writeln!(text, "Lesavka Diagnostics");
        let _ = writeln!(text, "client: v{}", self.client_version);
        let _ = writeln!(text, "server: {server_version} ({server_state})");
        let _ = writeln!(
            text,
            "session: routing={:?} view={:?} relay={} capture_power={}",
            self.routing,
            self.view_mode,
            if self.remote_active { "active" } else { "idle" },
            self.power_state
        );
        let _ = writeln!(
            text,
            "runtime: client CPU {:.1}% | server CPU {:.1}%",
            self.client_process_cpu_pct, self.server_process_cpu_pct
        );
        let _ = writeln!(text, "source feed: {}", self.preview_source);
        let _ = writeln!(text, "display limit: {}", self.client_display_limit);
        let _ = writeln!(text);
        let _ = writeln!(text, "left eye");
        let _ = writeln!(text, "  surface: {}", self.left_surface);
        let _ = writeln!(text, "  source: {}", self.left_feed_source);
        let _ = writeln!(text, "  capture: {}", self.left_capture_profile);
        let _ = writeln!(text, "  transport: {}", self.left_capture_transport);
        let _ = writeln!(text, "  breakout: {}", self.left_breakout_profile);
        let _ = writeln!(
            text,
            "  live: decoder={} spread={:.1}ms gaps={:.0}/{:.0}ms queue={}/{}",
            self.left_decoder_label,
            self.left_stream_spread_ms,
            self.left_packet_gap_peak_ms,
            self.left_present_gap_peak_ms,
            self.left_queue_depth,
            self.left_queue_peak
        );
        let _ = writeln!(text, "  stream caps: {}", self.left_stream_caps_label);
        let _ = writeln!(text, "  decoded caps: {}", self.left_decoded_caps_label);
        let _ = writeln!(text, "  rendered caps: {}", self.left_rendered_caps_label);
        let _ = writeln!(
            text,
            "  server: encoder={} cpu={:.1}% gaps={:.0}/{:.0}ms queue-peak={}",
            self.left_server_encoder_label,
            self.server_process_cpu_pct,
            self.left_server_source_gap_peak_ms,
            self.left_server_send_gap_peak_ms,
            self.left_server_queue_peak
        );
        let _ = writeln!(text, "right eye");
        let _ = writeln!(text, "  surface: {}", self.right_surface);
        let _ = writeln!(text, "  source: {}", self.right_feed_source);
        let _ = writeln!(text, "  capture: {}", self.right_capture_profile);
        let _ = writeln!(text, "  transport: {}", self.right_capture_transport);
        let _ = writeln!(text, "  breakout: {}", self.right_breakout_profile);
        let _ = writeln!(
            text,
            "  live: decoder={} spread={:.1}ms gaps={:.0}/{:.0}ms queue={}/{}",
            self.right_decoder_label,
            self.right_stream_spread_ms,
            self.right_packet_gap_peak_ms,
            self.right_present_gap_peak_ms,
            self.right_queue_depth,
            self.right_queue_peak
        );
        let _ = writeln!(text, "  stream caps: {}", self.right_stream_caps_label);
        let _ = writeln!(text, "  decoded caps: {}", self.right_decoded_caps_label);
        let _ = writeln!(text, "  rendered caps: {}", self.right_rendered_caps_label);
        let _ = writeln!(
            text,
            "  server: encoder={} cpu={:.1}% gaps={:.0}/{:.0}ms queue-peak={}",
            self.right_server_encoder_label,
            self.server_process_cpu_pct,
            self.right_server_source_gap_peak_ms,
            self.right_server_send_gap_peak_ms,
            self.right_server_queue_peak
        );
        let _ = writeln!(text);
        let _ = writeln!(text, "media staging");
        let _ = writeln!(
            text,
            "  camera: {} | quality={} | transport={} | enabled={}",
            self.selected_camera.as_deref().unwrap_or("auto"),
            self.camera_quality_label,
            self.upstream_camera_transport,
            self.media_channels.camera
        );
        let _ = writeln!(
            text,
            "  speaker: {} | volume={} | enabled={}",
            self.selected_speaker.as_deref().unwrap_or("auto"),
            self.audio_gain_label,
            self.media_channels.audio
        );
        let _ = writeln!(
            text,
            "  microphone: {} | gain={} | enabled={}",
            self.selected_microphone.as_deref().unwrap_or("auto"),
            self.mic_gain_label,
            self.media_channels.microphone
        );
        let _ = writeln!(
            text,
            "  uplink camera: {}",
            uplink_summary(&self.upstream_camera)
        );
        let _ = writeln!(
            text,
            "  uplink microphone: {}",
            uplink_summary(&self.upstream_microphone)
        );
        let _ = writeln!(text, "  uplink mode: {}", self.upstream_mode);
        let _ = writeln!(text, "av sync guardrails");
        let _ = writeln!(
            text,
            "  health: {} (target <= {:.0}ms skew, preferred <= {:.0}ms)",
            self.av_sync_health, AV_SYNC_WATCH_MS, AV_SYNC_GOOD_MS
        );
        let _ = writeln!(
            text,
            "  delivery skew: {:.1}ms | enqueue skew: {:.1}ms",
            self.av_delivery_skew_ms, self.av_enqueue_skew_ms
        );
        let _ = writeln!(
            text,
            "  camera ages: enqueue={:.1}ms delivery={:.1}ms",
            self.upstream_camera.latest_enqueue_age_ms, self.upstream_camera.latest_delivery_age_ms
        );
        let _ = writeln!(
            text,
            "  microphone ages: enqueue={:.1}ms delivery={:.1}ms",
            self.upstream_microphone.latest_enqueue_age_ms,
            self.upstream_microphone.latest_delivery_age_ms
        );
        let _ = writeln!(text, "server upstream planner");
        let _ = writeln!(
            text,
            "  status: {} | phase={} | session={}",
            if self.planner_available {
                "available"
            } else {
                "unavailable"
            },
            self.planner_phase,
            self.planner_session_id
        );
        let live_lag = self
            .planner_live_lag_ms
            .map(|value| format!("{value:.1}ms"))
            .unwrap_or_else(|| "pending".to_string());
        let planner_skew = self
            .planner_skew_ms
            .map(|value| format!("{value:+.1}ms audio-video"))
            .unwrap_or_else(|| "pending".to_string());
        let _ = writeln!(
            text,
            "  live lag: {live_lag} | planner skew: {planner_skew}"
        );
        let _ = writeln!(
            text,
            "  drops/heals: stale_audio={} stale_video={} skew_video={} reanchors={} freezes={} startup_timeouts={}",
            self.planner_stale_audio_drops,
            self.planner_stale_video_drops,
            self.planner_skew_video_drops,
            self.planner_freshness_reanchors,
            self.planner_video_freezes,
            self.planner_startup_timeouts
        );
        let _ = writeln!(text, "  detail: {}", self.planner_detail);
        let _ = writeln!(text, "calibration");
        let _ = writeln!(
            text,
            "  profile: {} | status={} | source={} | confidence={}",
            self.calibration_profile,
            if self.calibration_available {
                "available"
            } else {
                "unavailable"
            },
            self.calibration_source,
            self.calibration_confidence
        );
        let _ = writeln!(
            text,
            "  active: audio={:+.1}ms video={:+.1}ms",
            self.active_audio_offset_us as f64 / 1000.0,
            self.active_video_offset_us as f64 / 1000.0
        );
        let _ = writeln!(
            text,
            "  default: audio={:+.1}ms video={:+.1}ms | factory: audio={:+.1}ms video={:+.1}ms",
            self.default_audio_offset_us as f64 / 1000.0,
            self.default_video_offset_us as f64 / 1000.0,
            self.factory_audio_offset_us as f64 / 1000.0,
            self.factory_video_offset_us as f64 / 1000.0
        );
        let _ = writeln!(
            text,
            "  updated: {} | detail: {}",
            if self.calibration_updated_at.is_empty() {
                "unknown"
            } else {
                &self.calibration_updated_at
            },
            self.calibration_detail
        );
        let _ = writeln!(
            text,
            "  keyboard: {}",
            self.selected_keyboard.as_deref().unwrap_or("all")
        );
        let _ = writeln!(
            text,
            "  mouse: {}",
            self.selected_mouse.as_deref().unwrap_or("all")
        );
        let _ = writeln!(text);
        let _ = writeln!(text, "current UI state");
        let _ = writeln!(text, "  {}", self.status);
        let _ = writeln!(text);
        let _ = writeln!(text, "recent samples");
        if self.recent_samples.is_empty() {
            let _ = writeln!(
                text,
                "  no live RTT/probe-spread/loss samples yet; this report is currently a launcher state snapshot."
            );
        } else {
            for sample in &self.recent_samples {
                let _ = writeln!(
                    text,
                    "  rtt={:.1}ms probe-spread={:.1}ms input-floor={:.1}ms cpu={:.1}/{:.1}% probe-loss={:.1}% video-loss={:.1}% left={:.1}/{:.1}/{:.1}fps right={:.1}/{:.1}/{:.1}fps dropped={} queue={}/{} peaks=l{:.0}/{:.0}ms r{:.0}/{:.0}ms server=l{}:{:.0}/{:.0}/{} r{}:{:.0}/{:.0}/{}",
                    sample.rtt_ms,
                    sample.probe_spread_ms,
                    sample.input_latency_ms,
                    sample.client_process_cpu_pct,
                    sample.server_process_cpu_pct,
                    sample.probe_loss_pct,
                    sample.video_loss_pct,
                    sample.left_receive_fps,
                    sample.left_present_fps,
                    sample.left_server_fps,
                    sample.right_receive_fps,
                    sample.right_present_fps,
                    sample.right_server_fps,
                    sample.dropped_frames,
                    sample.queue_depth,
                    sample.left_queue_peak.max(sample.right_queue_peak),
                    sample.left_packet_gap_peak_ms,
                    sample.left_present_gap_peak_ms,
                    sample.right_packet_gap_peak_ms,
                    sample.right_present_gap_peak_ms,
                    sample.left_server_encoder_label,
                    sample.left_server_source_gap_peak_ms,
                    sample.left_server_send_gap_peak_ms,
                    sample.left_server_queue_peak,
                    sample.right_server_encoder_label,
                    sample.right_server_source_gap_peak_ms,
                    sample.right_server_send_gap_peak_ms,
                    sample.right_server_queue_peak
                );
                let _ = writeln!(
                    text,
                    "    uplink: mode={} cam={} mic={}",
                    sample.upstream_mode,
                    uplink_summary(&sample.upstream_camera),
                    uplink_summary(&sample.upstream_microphone)
                );
            }
        }
        let _ = writeln!(text);
        let _ = writeln!(text, "recommendations");
        for item in &self.recommendations {
            let _ = writeln!(text, "  - {item}");
        }
        if !self.notes.is_empty() {
            let _ = writeln!(text);
            let _ = writeln!(text, "notes");
            for item in &self.notes {
                let _ = writeln!(text, "  - {item}");
            }
        }
        let _ = writeln!(text);
        let _ = writeln!(text, "quality probe");
        let _ = writeln!(text, "  {}", self.probe_command);
        text
    }
}
fn uplink_summary(stream: &crate::uplink_telemetry::UpstreamStreamTelemetry) -> String {
    if !stream.enabled {
        return "disabled".to_string();
    }
    let connection = if stream.connected {
        "live"
    } else if stream.reconnect_count > 0 {
        "reconnecting"
    } else {
        "idle"
    };
    let error = if stream.last_error.is_empty() {
        "ok".to_string()
    } else {
        stream.last_error.clone()
    };
    format!(
        "{connection} queue={}/{} enq-age={:.0}/{:.0}ms delivery={:.0}/{:.0}ms block-peak={:.0}ms reconnects={} streamed={} drops(total/full/stale)={}/{}/{} error={error}",
        stream.queue_depth,
        stream.queue_peak,
        stream.latest_enqueue_age_ms,
        stream.enqueue_age_peak_ms,
        stream.latest_delivery_age_ms,
        stream.delivery_age_peak_ms,
        stream.enqueue_block_peak_ms,
        stream.reconnect_count,
        stream.packets_streamed,
        stream.dropped_packets,
        stream.dropped_queue_full_packets,
        stream.dropped_stale_packets
    )
}
