#include "app/diagnostic_ui_state.h"

#include <algorithm>
#include <chrono>
#include <ctime>
#include <iomanip>
#include <iterator>
#include <sstream>
#include <utility>

#include "backends/kernel_streaming_discovery.h"

namespace aptt {
namespace {

constexpr std::string_view kActiveBackendInterlockReason =
    "Stop or release the active backend before changing device, backend, or format.";
constexpr char kCloseGuardActiveBackendMessageJapanese[] =
    "\xE5\x86\x8D\xE7\x94\x9F\xE3\x81\xBE\xE3\x81\x9F\xE3\x81\xAF"
    "\xE4\xBF\x9D\xE6\x8C\x81\xE4\xB8\xAD\xE3\x81\xAE\xE3\x83\x87"
    "\xE3\x83\x90\xE3\x82\xA4\xE3\x82\xB9\xE3\x81\x8C\xE3\x81\x82"
    "\xE3\x82\x8A\xE3\x81\xBE\xE3\x81\x99\xE3\x80\x82\xE5\x85\x88"
    "\xE3\x81\xAB\xE5\x81\x9C\xE6\xAD\xA2\xE3\x81\xBE\xE3\x81\x9F"
    "\xE3\x81\xAF\xE8\xA7\xA3\xE6\x94\xBE\xE3\x81\x97\xE3\x81\xA6"
    "\xE3\x81\x8F\xE3\x81\xA0\xE3\x81\x95\xE3\x81\x84\xE3\x80\x82";
constexpr char kCloseGuardKsReleaseTimeoutMessageJapanese[] =
    "\x4B\x53\xE6\x9B\xB8\xE3\x81\x8D\xE8\xBE\xBC\xE3\x81\xBF"
    "\xE3\x82\xB9\xE3\x83\xAC\xE3\x83\x83\xE3\x83\x89\xE3\x81\xAE"
    "\xE7\xB5\x82\xE4\xBA\x86\xE5\xBE\x85\xE3\x81\xA1\xE3\x81\x8C"
    "\xE3\x82\xBF\xE3\x82\xA4\xE3\x83\xA0\xE3\x82\xA2\xE3\x82\xA6"
    "\xE3\x83\x88\xE3\x81\x97\xE3\x81\xA6\xE3\x81\x84\xE3\x81\xBE"
    "\xE3\x81\x99\xE3\x80\x82\xE5\xAE\x89\xE5\x85\xA8\xE3\x81\xAB"
    "\xE8\xA7\xA3\xE6\x94\xBE\xE3\x81\xA7\xE3\x81\x8D\xE3\x81\xA6"
    "\xE3\x81\x84\xE3\x81\xAA\xE3\x81\x84\xE5\x8F\xAF\xE8\x83\xBD"
    "\xE6\x80\xA7\xE3\x81\x8C\xE3\x81\x82\xE3\x82\x8A\xE3\x81\xBE"
    "\xE3\x81\x99\xE3\x80\x82\xE5\x86\x8D\xE5\xBA\xA6\xE3\x80\x81"
    "\xE8\xA7\xA3\xE6\x94\xBE\xE3\x82\x92\xE8\xA9\xA6\xE3\x81\x97"
    "\xE3\x81\xA6\xE3\x81\x8F\xE3\x81\xA0\xE3\x81\x95\xE3\x81\x84"
    "\xE3\x80\x82";
constexpr char kCloseGuardActiveBackendMessageEnglish[] =
    "A playback or held device is still active. Stop or release it before closing.";
constexpr char kCloseGuardKsReleaseTimeoutMessageEnglish[] =
    "The Kernel Streaming write thread is still waiting to exit. The device may not be safely released yet. Try release again.";

const char* ToString(DiagnosticLogFormat format) {
  switch (format) {
    case DiagnosticLogFormat::kJsonl:
      return "jsonl";
    case DiagnosticLogFormat::kText:
      return "text";
    case DiagnosticLogFormat::kCsv:
      return "csv";
  }
  return "unknown";
}

const char* ToString(DiagnosticLogLevel level) {
  switch (level) {
    case DiagnosticLogLevel::kNormal:
      return "normal";
    case DiagnosticLogLevel::kVerbose:
      return "verbose";
    case DiagnosticLogLevel::kCallbackTrace:
      return "callback-trace";
  }
  return "unknown";
}

const char* ToString(DiagnosticCallbackMode mode) {
  switch (mode) {
    case DiagnosticCallbackMode::kTimerDriven:
      return "timer-driven";
    case DiagnosticCallbackMode::kEventDriven:
      return "event-driven";
    case DiagnosticCallbackMode::kDriverCallback:
      return "driver-callback";
  }
  return "unknown";
}

bool IsFullReleaseMode(HoldMode mode) {
  return mode == HoldMode::kReleaseAfterDrain ||
         mode == HoldMode::kImmediateRelease;
}

std::optional<std::uint64_t> SignalTargetFrames(const PlaybackConfig& config) {
  if (config.continuous) {
    return std::nullopt;
  }
  return std::max<std::uint64_t>(
      1,
      (static_cast<std::uint64_t>(config.format.sample_rate_hz) *
       config.duration_ms) /
          1000);
}

std::uint64_t KeepAliveOrSilenceFramesSubmitted(const RealtimeStats& stats) {
  if (stats.frames_submitted < stats.frames_generated) {
    return 0;
  }
  return stats.frames_submitted - stats.frames_generated;
}

std::filesystem::path BundleBasePath(const DiagnosticUiSettings& settings) {
  const auto root = settings.log_directory.empty()
      ? std::filesystem::path("diagnostic_bundles")
      : settings.log_directory;
  if (settings.overwrite_logs) {
    return root / "diagnostic_bundle_latest";
  }

  const auto first = root / "diagnostic_bundle";
  if (!std::filesystem::exists(first) &&
      !std::filesystem::exists(first.string() + ".zip")) {
    return first;
  }
  for (int index = 1; index < 10000; ++index) {
    std::ostringstream suffix;
    suffix << "diagnostic_bundle_" << std::setw(3) << std::setfill('0') << index;
    const auto candidate = root / suffix.str();
    if (!std::filesystem::exists(candidate) &&
        !std::filesystem::exists(candidate.string() + ".zip")) {
      return candidate;
    }
  }
  return root / "diagnostic_bundle_overflow";
}

std::string BuildUiBundleSummary(const PlaybackConfig& config,
                                 const RealtimeStats& stats,
                                 std::string_view status_text,
                                 bool last_run_ok) {
  std::ostringstream out;
  out << "Audio Path Tone Tester diagnostic bundle\n";
  out << "status=" << status_text << "\n";
  out << "result=" << (last_run_ok ? "ok" : "failed") << "\n";
  out << "backend=" << ToString(config.backend) << "\n";
  out << "device_id=" << config.device.stable_id << "\n";
  out << "device_name=" << config.device.display_name << "\n";
  out << "signal=" << ToString(config.format.signal_mode) << "\n";
  out << "sample_rate_hz=" << config.format.sample_rate_hz << "\n";
  out << "sample_type=" << ToString(config.format.sample_type) << "\n";
  out << "channel_count=" << config.format.channels.channel_count << "\n";
  out << "hold_mode=" << ToString(config.hold_mode) << "\n";
  out << "left_channel=" << (config.left_channel_enabled ? "on" : "off") << "\n";
  out << "right_channel=" << (config.right_channel_enabled ? "on" : "off") << "\n";
  out << "invert_right=" << (config.invert_right_phase ? "true" : "false") << "\n";
  out << "right_phase_offset_degrees="
      << config.right_channel_phase_offset_degrees << "\n";
  out << "frames_generated=" << stats.frames_generated << "\n";
  out << "frames_submitted=" << stats.frames_submitted << "\n";
  const auto signal_target_frames = SignalTargetFrames(config);
  if (signal_target_frames) {
    out << "signal_target_frames=" << *signal_target_frames << "\n";
    out << "signal_complete="
        << (stats.frames_generated >= *signal_target_frames ? "true" : "false")
        << "\n";
  } else {
    out << "signal_complete=continuous\n";
  }
  out << "keep_alive_or_silence_frames_submitted="
      << KeepAliveOrSilenceFramesSubmitted(stats) << "\n";
  out << "frames_accepted=" << stats.frames_accepted << "\n";
  out << "callback_count=" << stats.callback_count << "\n";
  out << "underrun_count=" << stats.underrun_count << "\n";
  out << "discontinuity_count=" << stats.discontinuity_count << "\n";
  out << "device_invalidated_count=" << stats.device_invalidated_count << "\n";
  return out.str();
}

std::string EscapeJsonString(std::string_view value) {
  std::ostringstream out;
  for (const unsigned char ch : value) {
    switch (ch) {
      case '"':
        out << "\\\"";
        break;
      case '\\':
        out << "\\\\";
        break;
      case '\b':
        out << "\\b";
        break;
      case '\f':
        out << "\\f";
        break;
      case '\n':
        out << "\\n";
        break;
      case '\r':
        out << "\\r";
        break;
      case '\t':
        out << "\\t";
        break;
      default:
        if (ch < 0x20) {
          out << "\\u" << std::hex << std::setw(4) << std::setfill('0')
              << static_cast<int>(ch) << std::dec << std::setfill(' ');
        } else {
          out << static_cast<char>(ch);
        }
        break;
    }
  }
  return out.str();
}

std::tm UtcTm(std::time_t value) {
  std::tm tm{};
#if defined(_MSC_VER)
  gmtime_s(&tm, &value);
#else
  if (const std::tm* utc = std::gmtime(&value)) {
    tm = *utc;
  }
#endif
  return tm;
}

std::string FormatUtcTimestamp(
    std::chrono::system_clock::time_point timestamp) {
  const auto time = std::chrono::system_clock::to_time_t(timestamp);
  const auto tm = UtcTm(time);
  std::ostringstream out;
  out << std::put_time(&tm, "%Y-%m-%dT%H:%M:%SZ");
  return out.str();
}

std::string MakeUiSessionId(std::chrono::system_clock::time_point timestamp) {
  const auto milliseconds = std::chrono::duration_cast<std::chrono::milliseconds>(
      timestamp.time_since_epoch()).count();
  return "ui-" + std::to_string(milliseconds);
}

bool IsPcmSampleType(SampleType sample_type) {
  switch (sample_type) {
    case SampleType::kInt16:
    case SampleType::kInt24Packed:
    case SampleType::kInt24In32:
    case SampleType::kInt32:
    case SampleType::kFloat32:
    case SampleType::kFloat64:
      return true;
    case SampleType::kDsd1BitLsbFirst:
    case SampleType::kDsd1BitMsbFirst:
    case SampleType::kDsd8Bit:
      return false;
  }
  return false;
}

bool SameFormat(const FormatDescriptor& left, const FormatDescriptor& right) {
  return left.signal_mode == right.signal_mode &&
         left.sample_rate_hz == right.sample_rate_hz &&
         left.sample_type == right.sample_type &&
         left.valid_bits_per_sample == right.valid_bits_per_sample &&
         left.container_bits_per_sample == right.container_bits_per_sample &&
         left.channels.channel_count == right.channels.channel_count &&
         left.channels.channel_mask == right.channels.channel_mask &&
         left.dsd_rate_multiplier == right.dsd_rate_multiplier;
}

bool IsMixFormatProbe(const CapabilityProbeRecord& probe) {
  const auto api = probe.backend_fields.find("api");
  return api != probe.backend_fields.end() &&
         api->second == "IAudioClient::GetMixFormat";
}

bool IsWasapiEndpointMode(BackendApi backend) {
  return backend == BackendApi::kWasapiShared ||
         backend == BackendApi::kWasapiExclusive;
}

bool IsFormatChangingSettingDifferent(const DiagnosticUiSettings& left,
                                      const DiagnosticUiSettings& right) {
  return left.requested_backend != right.requested_backend ||
         left.requested_signal != right.requested_signal ||
         left.requested_sample_type != right.requested_sample_type ||
         left.requested_sample_rate_hz != right.requested_sample_rate_hz ||
         left.requested_valid_bits != right.requested_valid_bits ||
         left.requested_container_bits != right.requested_container_bits ||
         left.requested_channel_count != right.requested_channel_count ||
         left.requested_channel_mask != right.requested_channel_mask ||
         left.requested_dsd_rate_multiplier != right.requested_dsd_rate_multiplier;
}

bool IsRunConfigSettingDifferent(const DiagnosticUiSettings& left,
                                 const DiagnosticUiSettings& right) {
  return left.frequency_hz != right.frequency_hz ||
         left.amplitude_dbfs != right.amplitude_dbfs ||
         left.duration_ms != right.duration_ms ||
         left.continuous != right.continuous ||
         left.fade_in_ms != right.fade_in_ms ||
         left.fade_out_ms != right.fade_out_ms ||
         left.silence_preroll_ms != right.silence_preroll_ms ||
         left.silence_postroll_ms != right.silence_postroll_ms ||
         left.left_channel_enabled != right.left_channel_enabled ||
         left.right_channel_enabled != right.right_channel_enabled ||
         left.invert_right_phase != right.invert_right_phase ||
         left.phase_offset_degrees != right.phase_offset_degrees ||
         left.mme_buffer_count != right.mme_buffer_count ||
         left.mme_buffer_duration_ms != right.mme_buffer_duration_ms ||
         left.directsound_secondary_buffer_duration_ms !=
             right.directsound_secondary_buffer_duration_ms ||
         left.directsound_write_chunk_ms != right.directsound_write_chunk_ms ||
         left.directsound_cursor_poll_interval_ms !=
             right.directsound_cursor_poll_interval_ms ||
         left.wasapi_shared_buffer_duration_ms !=
             right.wasapi_shared_buffer_duration_ms ||
         left.wasapi_shared_render_poll_interval_ms !=
             right.wasapi_shared_render_poll_interval_ms ||
         left.wasapi_exclusive_buffer_duration_ms !=
             right.wasapi_exclusive_buffer_duration_ms ||
         left.wasapi_exclusive_periodicity_ms !=
             right.wasapi_exclusive_periodicity_ms ||
         left.wasapi_exclusive_render_poll_interval_ms !=
             right.wasapi_exclusive_render_poll_interval_ms ||
         left.wasapi_exclusive_event_callback_enabled !=
             right.wasapi_exclusive_event_callback_enabled ||
         left.wasapi_exclusive_alignment_retry_enabled !=
             right.wasapi_exclusive_alignment_retry_enabled ||
         left.wasapi_exclusive_event_timeout_ms !=
             right.wasapi_exclusive_event_timeout_ms ||
         left.audio_thread_mmcss_enabled !=
             right.audio_thread_mmcss_enabled ||
         left.audio_thread_mmcss_task_name !=
             right.audio_thread_mmcss_task_name ||
         left.audio_thread_mmcss_priority !=
             right.audio_thread_mmcss_priority ||
         left.asio_use_output_ready_if_supported !=
             right.asio_use_output_ready_if_supported ||
         left.high_load_diagnostics_enabled !=
             right.high_load_diagnostics_enabled ||
         left.high_load_risk_acknowledged !=
             right.high_load_risk_acknowledged ||
         left.high_load_render_delay_ms !=
             right.high_load_render_delay_ms ||
         left.high_load_delay_every_callbacks !=
             right.high_load_delay_every_callbacks ||
         left.hold_mode != right.hold_mode ||
         left.keep_alive_stream_enabled != right.keep_alive_stream_enabled ||
         left.drain_before_stop != right.drain_before_stop ||
         left.drain_timeout_ms != right.drain_timeout_ms ||
         left.release_cooldown_ms != right.release_cooldown_ms ||
         left.reacquire_cooldown_ms != right.reacquire_cooldown_ms ||
         left.max_reacquire_attempts != right.max_reacquire_attempts ||
         left.rapid_format_cycle_guard != right.rapid_format_cycle_guard ||
         left.manual_known_problem_device != right.manual_known_problem_device ||
         left.log_directory != right.log_directory ||
         left.log_format != right.log_format ||
         left.log_level != right.log_level ||
         left.initialization_dump_enabled != right.initialization_dump_enabled ||
         left.callback_event_logging != right.callback_event_logging ||
         left.callback_trace_limit != right.callback_trace_limit ||
         left.periodic_summary_interval_ms != right.periodic_summary_interval_ms ||
         left.overwrite_logs != right.overwrite_logs ||
         left.automatic_format_matrix_enabled != right.automatic_format_matrix_enabled ||
         left.automatic_buffer_ramp_enabled != right.automatic_buffer_ramp_enabled ||
         left.automatic_start_stop_stress_enabled !=
             right.automatic_start_stop_stress_enabled ||
         left.automatic_reinitialize_enabled != right.automatic_reinitialize_enabled;
}

bool IsOnlyUnsafeReleaseAcknowledgementDifferent(
    const DiagnosticUiSettings& current,
    const DiagnosticUiSettings& next) {
  if (current.expert_unsafe_release_ack == next.expert_unsafe_release_ack) {
    return false;
  }
  auto current_with_next_ack = current;
  current_with_next_ack.expert_unsafe_release_ack =
      next.expert_unsafe_release_ack;
  return !IsFormatChangingSettingDifferent(current_with_next_ack, next) &&
         !IsRunConfigSettingDifferent(current_with_next_ack, next);
}

std::string BackendFieldValue(const CapabilityProbeRecord& probe,
                              const std::string& key) {
  const auto it = probe.backend_fields.find(key);
  return it == probe.backend_fields.end() ? std::string{} : it->second;
}

std::string KernelStreamingProbeResultLevel(
    const CapabilityProbeRecord& probe) {
  const auto explicit_level = BackendFieldValue(probe, "ks_result_level");
  if (!explicit_level.empty()) {
    return explicit_level;
  }
  if (BackendFieldValue(probe, "starts_stream") == "true") {
    return "start_verified";
  }
  if (BackendFieldValue(probe, "creates_pin") == "true" &&
      probe.support == CapabilitySupport::kSupported) {
    return "pin_create_verified";
  }
  if (probe.support == CapabilitySupport::kSupported &&
      probe.accepted_format) {
    return "data_range_match";
  }
  return {};
}

bool IsKernelStreamingRenderPlaybackProbe(
    const CapabilityProbeRecord& probe) {
  const auto explicit_candidate =
      BackendFieldValue(probe, "ks_render_candidate");
  if (explicit_candidate == "true") {
    return true;
  }
  if (explicit_candidate == "false") {
    return false;
  }

  const auto dataflow = BackendFieldValue(probe, "ks_pin_dataflow");
  const auto communication = BackendFieldValue(probe, "ks_pin_communication");
  return dataflow == "render" &&
         (communication == "sink" || communication == "both");
}

bool IsKernelStreamingPlaybackUnimplementedModel(
    const CapabilityProbeRecord& probe) {
  if (BackendFieldValue(probe, "ks_playback_implementation") !=
      "unimplemented") {
    return false;
  }
  const auto model = BackendFieldValue(probe, "ks_streaming_model");
  return model == "standard_looped";
}

bool IsPlayableAcceptedFormatForBackend(BackendApi backend,
                                        const FormatDescriptor& format,
                                        const CapabilityProbeRecord& probe) {
  if (IsMixFormatProbe(probe)) {
    return false;
  }
  if (backend == BackendApi::kMme) {
    return probe.support == CapabilitySupport::kSupported &&
           IsMmePcmPlaybackFormat(format);
  }
  if (backend == BackendApi::kDirectSound) {
    return probe.support == CapabilitySupport::kSupported &&
           IsDirectSoundPcmPlaybackFormat(format);
  }
  if (backend == BackendApi::kWasapiShared) {
    return (probe.support == CapabilitySupport::kSupported ||
            probe.support == CapabilitySupport::kClosestMatch) &&
           IsWasapiSharedPcmPlaybackFormat(format);
  }
  if (backend == BackendApi::kWasapiExclusive) {
    return probe.support == CapabilitySupport::kSupported &&
           (IsWasapiExclusivePlaybackFormat(format) ||
            IsWasapiExclusiveDopCarrierFormat(format));
  }
  if (backend == BackendApi::kAsio) {
    return probe.support == CapabilitySupport::kSupported &&
           (IsAsioPcmPlaybackFormat(format) ||
            IsAsioDopCarrierFormat(format) ||
            IsAsioNativeDsdPlaybackFormat(format));
  }
  if (backend == BackendApi::kKernelStreaming) {
    return probe.support == CapabilitySupport::kSupported &&
           IsKernelStreamingRenderPlaybackProbe(probe) &&
           !IsKernelStreamingPlaybackUnimplementedModel(probe) &&
           (BackendFieldValue(probe, "ks_streaming_model").empty() ||
            BackendFieldValue(probe, "ks_streaming_model") ==
                "standard_packet" ||
            BackendFieldValue(probe, "ks_streaming_model") ==
                "wavert_cyclic") &&
           IsKernelStreamingPlaybackFormat(format);
  }
  return false;
}

bool IsKernelStreamingDataRangeOnlyCandidate(
    const CapabilityProbeRecord& probe) {
  return KernelStreamingProbeResultLevel(probe) == "data_range_match";
}

bool IsConfirmedSupportedFormatProbe(BackendApi backend,
                                     const CapabilityProbeRecord& probe) {
  if (!probe.accepted_format) {
    return false;
  }
  if (!IsPlayableAcceptedFormatForBackend(
          backend,
          *probe.accepted_format,
          probe)) {
    return false;
  }
  if (backend == BackendApi::kKernelStreaming &&
      IsKernelStreamingDataRangeOnlyCandidate(probe)) {
    return false;
  }
  if (backend == BackendApi::kKernelStreaming &&
      IsKernelStreamingPlaybackUnimplementedModel(probe)) {
    return false;
  }
  return true;
}

std::string CandidateOnlyReason(const CapabilityProbeRecord& probe) {
  std::ostringstream out;
  out << "candidate-only evidence";
  const auto level = KernelStreamingProbeResultLevel(probe);
  if (!level.empty()) {
    out << ": ks_result_level=" << level;
  }
  if (!probe.detail.empty()) {
    out << ": " << probe.detail;
  }
  return out.str();
}

FormatProbeResult FormatProbeForRun(
    const PlaybackConfig& config,
    const std::optional<SelectedTestCondition>& selected_condition,
    bool start_verified) {
  FormatProbeResult probe;
  probe.requested = selected_condition
      ? selected_condition->requested_format
      : config.format;

  const bool ks_candidate =
      config.backend == BackendApi::kKernelStreaming &&
      selected_condition &&
      selected_condition->capability_status == CapabilityCellStatus::kDataRangeMatch;
  if (ks_candidate && !start_verified) {
    std::ostringstream reason;
    reason << "Kernel Streaming data_range_match is candidate evidence only";
    const auto level = selected_condition->raw_backend_fields.find(
        "ks_result_level");
    if (level != selected_condition->raw_backend_fields.end()) {
      reason << ": ks_result_level=" << level->second;
    }
    probe.rejection_reasons.push_back(reason.str());
    return probe;
  }

  probe.supported_formats.push_back(config.format);
  return probe;
}

std::string BuildSelectedConditionJson(
    const SelectedTestCondition& condition) {
  std::ostringstream out;
  out << "{\n";
  out << "  \"backend\": \"" << ToString(condition.backend) << "\",\n";
  out << "  \"backend_device_id\": \""
      << EscapeJsonString(condition.backend_device_id) << "\",\n";
  out << "  \"backend_device_name\": \""
      << EscapeJsonString(condition.backend_device_name) << "\",\n";
  out << "  \"matrix_scan_revision\": "
      << condition.matrix_scan_revision << ",\n";
  out << "  \"matrix_row\": " << condition.matrix_row << ",\n";
  out << "  \"matrix_column\": " << condition.matrix_column << ",\n";
  out << "  \"capability_status\": \""
      << ToString(condition.capability_status) << "\",\n";
  out << "  \"requested\": {\n";
  out << "    \"signal\": \"" << ToString(condition.requested_format.signal_mode)
      << "\",\n";
  out << "    \"sample_rate_hz\": "
      << condition.requested_format.sample_rate_hz << ",\n";
  out << "    \"sample_type\": \""
      << ToString(condition.requested_format.sample_type) << "\",\n";
  out << "    \"valid_bits_per_sample\": "
      << condition.requested_format.valid_bits_per_sample << ",\n";
  out << "    \"container_bits_per_sample\": "
      << condition.requested_format.container_bits_per_sample << ",\n";
  out << "    \"channel_count\": "
      << condition.requested_format.channels.channel_count << "\n";
  out << "  },\n";
  out << "  \"accepted\": {\n";
  out << "    \"signal\": \""
      << ToString(condition.accepted_playback_format.signal_mode) << "\",\n";
  out << "    \"sample_rate_hz\": "
      << condition.accepted_playback_format.sample_rate_hz << ",\n";
  out << "    \"sample_type\": \""
      << ToString(condition.accepted_playback_format.sample_type) << "\",\n";
  out << "    \"valid_bits_per_sample\": "
      << condition.accepted_playback_format.valid_bits_per_sample << ",\n";
  out << "    \"container_bits_per_sample\": "
      << condition.accepted_playback_format.container_bits_per_sample << ",\n";
  out << "    \"channel_count\": "
      << condition.accepted_playback_format.channels.channel_count << "\n";
  out << "  },\n";
  out << "  \"backend_fields\": {";
  bool first = true;
  for (const auto& [key, value] : condition.raw_backend_fields) {
    out << (first ? "\n" : ",\n");
    first = false;
    out << "    \"" << EscapeJsonString(key) << "\": \""
        << EscapeJsonString(value) << "\"";
  }
  if (!condition.raw_backend_fields.empty()) {
    out << "\n  ";
  }
  out << "}\n";
  out << "}\n";
  return out.str();
}

AcceptedFormatSelectionKind SelectionKindForProbe(
    const CapabilityProbeRecord& probe,
    const FormatDescriptor& current_request) {
  if (IsMixFormatProbe(probe)) {
    return AcceptedFormatSelectionKind::kUserMixFormat;
  }
  if (probe.support == CapabilitySupport::kClosestMatch) {
    return AcceptedFormatSelectionKind::kUserClosestMatch;
  }
  if (probe.requested_format && probe.accepted_format &&
      SameFormat(*probe.requested_format, *probe.accepted_format) &&
      SameFormat(*probe.requested_format, current_request)) {
    return AcceptedFormatSelectionKind::kRequestedExact;
  }
  return AcceptedFormatSelectionKind::kUserFallback;
}

const char* ToString(AcceptedFormatSelectionKind kind) {
  switch (kind) {
    case AcceptedFormatSelectionKind::kNone:
      return "none";
    case AcceptedFormatSelectionKind::kRequestedExact:
      return "playable exact";
    case AcceptedFormatSelectionKind::kUserFallback:
      return "playable fallback selected";
    case AcceptedFormatSelectionKind::kUserMixFormat:
      return "mix format reference selected";
    case AcceptedFormatSelectionKind::kUserClosestMatch:
      return "playable closest match selected";
  }
  return "unknown";
}

void PushUniqueFormat(std::vector<FormatDescriptor>& formats,
                      const FormatDescriptor& candidate) {
  const auto found = std::find_if(
      formats.begin(),
      formats.end(),
      [&](const FormatDescriptor& existing) {
        return SameFormat(existing, candidate);
      });
  if (found == formats.end()) {
    formats.push_back(candidate);
  }
}

FormatDescriptor MakeMatrixPcmCandidate(std::uint32_t sample_rate_hz,
                                        SampleType sample_type,
                                        std::uint32_t valid_bits,
                                        std::uint32_t container_bits) {
  FormatDescriptor descriptor;
  descriptor.signal_mode = SignalMode::kPcm;
  descriptor.sample_rate_hz = sample_rate_hz;
  descriptor.sample_type = sample_type;
  descriptor.valid_bits_per_sample = valid_bits;
  descriptor.container_bits_per_sample = container_bits;
  descriptor.channels.channel_count = 2;
  descriptor.channels.channel_mask = 3;
  return descriptor;
}

FormatDescriptor MakeMatrixDopCandidate(std::uint32_t dsd_rate_multiplier) {
  DopConfig config;
  config.dsd_rate_multiplier = dsd_rate_multiplier;
  config.channel_count = 2;
  return MakeDopCarrierFormat(config);
}

FormatDescriptor MakeMatrixNativeDsdCandidate(
    std::uint32_t dsd_rate_multiplier) {
  NativeDsdConfig config;
  config.dsd_rate_multiplier = dsd_rate_multiplier;
  config.channel_count = 2;
  config.sample_type = SampleType::kDsd1BitLsbFirst;
  return MakeNativeDsdFormat(config);
}

std::vector<std::uint32_t> PcmMatrixSampleRates() {
  return {
      44100, 48000, 88200, 96000, 176400, 192000, 352800,
      384000, 705600, 768000, 786000, 1411200, 1536000};
}

std::vector<std::uint32_t> DsdRateMultipliers() {
  return {64, 128, 256, 512, 1024, 2048};
}

std::vector<std::uint32_t> CapabilityMatrixSampleRateColumns() {
  std::vector<std::uint32_t> columns = PcmMatrixSampleRates();
  for (const auto dsd_rate_multiplier : DsdRateMultipliers()) {
    columns.push_back(DopCarrierSampleRateHz(dsd_rate_multiplier));
    columns.push_back(NativeDsdRateHz(dsd_rate_multiplier));
  }
  std::sort(columns.begin(), columns.end());
  columns.erase(std::unique(columns.begin(), columns.end()), columns.end());
  return columns;
}

std::vector<FormatDescriptor> CapabilityMatrixRows() {
  std::vector<FormatDescriptor> rows;
  rows.push_back(MakeMatrixPcmCandidate(0, SampleType::kInt16, 16, 16));
  rows.push_back(MakeMatrixPcmCandidate(0, SampleType::kInt24Packed, 24, 24));
  rows.push_back(MakeMatrixPcmCandidate(0, SampleType::kInt24In32, 24, 32));
  rows.push_back(MakeMatrixPcmCandidate(0, SampleType::kFloat32, 32, 32));
  rows.push_back(MakeMatrixPcmCandidate(0, SampleType::kInt32, 32, 32));

  DopConfig dop;
  dop.dsd_rate_multiplier = 64;
  dop.channel_count = 2;
  rows.push_back(MakeDopCarrierFormat(dop));

  NativeDsdConfig native_dsd;
  native_dsd.dsd_rate_multiplier = 64;
  native_dsd.channel_count = 2;
  native_dsd.sample_type = SampleType::kDsd1BitLsbFirst;
  rows.push_back(MakeNativeDsdFormat(native_dsd));
  native_dsd.sample_type = SampleType::kDsd1BitMsbFirst;
  rows.push_back(MakeNativeDsdFormat(native_dsd));
  native_dsd.sample_type = SampleType::kDsd8Bit;
  rows.push_back(MakeNativeDsdFormat(native_dsd));
  return rows;
}

std::optional<std::uint32_t> DopMultiplierFromCarrierRate(
    std::uint32_t sample_rate_hz) {
  for (const auto dsd_rate_multiplier : DsdRateMultipliers()) {
    if (DopCarrierSampleRateHz(dsd_rate_multiplier) == sample_rate_hz) {
      return dsd_rate_multiplier;
    }
  }
  return std::nullopt;
}

std::optional<std::uint32_t> NativeDsdMultiplierFromRate(
    std::uint32_t sample_rate_hz) {
  for (const auto dsd_rate_multiplier : DsdRateMultipliers()) {
    if (NativeDsdRateHz(dsd_rate_multiplier) == sample_rate_hz) {
      return dsd_rate_multiplier;
    }
  }
  return std::nullopt;
}

std::optional<FormatDescriptor> MatrixFormatForCell(
    const FormatDescriptor& row_format,
    std::uint32_t sample_rate_hz) {
  if (row_format.signal_mode == SignalMode::kPcm) {
    auto format = row_format;
    format.sample_rate_hz = sample_rate_hz;
    return format;
  }
  if (row_format.signal_mode == SignalMode::kDop) {
    const auto multiplier = DopMultiplierFromCarrierRate(sample_rate_hz);
    if (!multiplier) {
      return std::nullopt;
    }
    DopConfig config;
    config.dsd_rate_multiplier = *multiplier;
    config.channel_count = row_format.channels.channel_count;
    config.marker_starts_with_0x05 = row_format.dop_marker_starts_with_0x05;
    return MakeDopCarrierFormat(config);
  }
  if (row_format.signal_mode == SignalMode::kAsioNativeDsd) {
    const auto multiplier = NativeDsdMultiplierFromRate(sample_rate_hz);
    if (!multiplier) {
      return std::nullopt;
    }
    NativeDsdConfig config;
    config.dsd_rate_multiplier = *multiplier;
    config.channel_count = row_format.channels.channel_count;
    config.sample_type = row_format.sample_type;
    return MakeNativeDsdFormat(config);
  }
  return std::nullopt;
}

bool CanMapSelectedDeviceToBackend(const DeviceInfo& selected_device,
                                   BackendApi backend) {
  return selected_device.backend == backend;
}

DeviceInfo MatrixDeviceForBackend(const DeviceInfo& selected_device,
                                  BackendApi backend) {
  DeviceInfo mapped = selected_device;
  mapped.backend = backend;
  return mapped;
}

bool DeviceMatchesRequestedBackend(const DeviceInfo& device,
                                   BackendApi requested_backend) {
  return device.backend == requested_backend;
}

void RetagWasapiSnapshotForRequestedMode(DiscoverySnapshot& snapshot,
                                         BackendApi requested_backend) {
  if (!IsWasapiEndpointMode(requested_backend)) {
    return;
  }
  snapshot.backend = requested_backend;
  for (auto& device : snapshot.devices) {
    device.device.backend = requested_backend;
  }
}

bool IsBackendFormatCombinationApplicable(BackendApi backend,
                                          const FormatDescriptor& format);

bool SnapshotHasFormatProbeRows(const DeviceCapabilitySnapshot& snapshot) {
  for (const auto& probe : snapshot.probes) {
    if (probe.kind == CapabilityProbeKind::kFormatSupport) {
      return true;
    }
  }
  return false;
}

bool MatrixRowsContainSignal(const std::vector<FormatDescriptor>& rows,
                             SignalMode signal_mode) {
  for (const auto& row : rows) {
    if (row.signal_mode == signal_mode) {
      return true;
    }
  }
  return false;
}

std::vector<FormatDescriptor> MatrixProbeCandidatesForBackend(
    const std::vector<FormatDescriptor>& rows,
    const std::vector<std::uint32_t>& sample_rate_columns,
    BackendApi backend) {
  std::vector<FormatDescriptor> candidates;
  for (const auto& row : rows) {
    for (const auto sample_rate_hz : sample_rate_columns) {
      const auto cell_format = MatrixFormatForCell(row, sample_rate_hz);
      if (!cell_format) {
        continue;
      }
      if (!IsBackendFormatCombinationApplicable(backend, *cell_format)) {
        continue;
      }
      if ((backend == BackendApi::kMme ||
           backend == BackendApi::kDirectSound) &&
          cell_format->signal_mode != SignalMode::kPcm) {
        continue;
      }
      PushUniqueFormat(candidates, *cell_format);
    }
  }
  return candidates;
}

void AddAsioPcmProbeRecords(DeviceCapabilitySnapshot& snapshot,
                            const FormatProbeResult& probe_result) {
  for (const auto& format : probe_result.supported_formats) {
    CapabilityProbeRecord record;
    record.kind = CapabilityProbeKind::kFormatSupport;
    record.support = CapabilitySupport::kSupported;
    record.requested_format = format;
    record.accepted_format = format;
    record.detail = "ASIO PCM output format accepted for selected driver";
    record.backend_fields["api"] = "ASIO driver query";
    record.backend_fields["creates_buffers"] = "false";
    record.backend_fields["starts_stream"] = "false";
    record.backend_fields["opens_control_panel"] = "false";
    snapshot.probes.push_back(std::move(record));
  }
  if (!probe_result.supported_formats.empty()) {
    return;
  }

  CapabilityProbeRecord record;
  record.kind = CapabilityProbeKind::kFormatSupport;
  record.support = CapabilitySupport::kFailed;
  record.requested_format = probe_result.requested;
  record.detail = probe_result.rejection_reasons.empty()
      ? "ASIO PCM probe did not return a supported format"
      : probe_result.rejection_reasons.front();
  record.backend_fields["api"] = "ASIO driver query";
  record.backend_fields["creates_buffers"] = "false";
  record.backend_fields["starts_stream"] = "false";
  record.backend_fields["opens_control_panel"] = "false";
  snapshot.probes.push_back(std::move(record));
}

void AddUnsupportedAsioPcmMatrixRows(
    DeviceCapabilitySnapshot& snapshot,
    const FormatProbeResult& probe_result,
    const std::vector<FormatDescriptor>& candidate_formats) {
  if (probe_result.supported_formats.empty()) {
    return;
  }

  for (const auto& candidate : candidate_formats) {
    if (candidate.signal_mode != SignalMode::kPcm ||
        !IsAsioPcmPlaybackFormat(candidate)) {
      continue;
    }
    const auto supported = std::find_if(
        probe_result.supported_formats.begin(),
        probe_result.supported_formats.end(),
        [&](const FormatDescriptor& supported_format) {
          return SameFormat(supported_format, candidate);
        });
    if (supported != probe_result.supported_formats.end()) {
      continue;
    }

    CapabilityProbeRecord record;
    record.kind = CapabilityProbeKind::kFormatSupport;
    record.support = CapabilitySupport::kUnsupported;
    record.requested_format = candidate;
    record.detail =
        "ASIO driver did not report this PCM sample type/rate for the selected output channel";
    record.backend_fields["api"] = "ASIO driver query";
    record.backend_fields["creates_buffers"] = "false";
    record.backend_fields["starts_stream"] = "false";
    record.backend_fields["opens_control_panel"] = "false";
    snapshot.probes.push_back(std::move(record));
  }
}

void AddAsioDopProbeRecords(DeviceCapabilitySnapshot& snapshot,
                            const FormatProbeResult& probe_result) {
  for (const auto& format : probe_result.supported_formats) {
    CapabilityProbeRecord record;
    record.kind = CapabilityProbeKind::kFormatSupport;
    record.support = CapabilitySupport::kSupported;
    record.requested_format = probe_result.requested;
    record.accepted_format = format;
    record.detail = "ASIO DoP PCM carrier format accepted for selected driver";
    record.backend_fields["api"] = "ASIO DoP carrier query";
    record.backend_fields["creates_buffers"] = "false";
    record.backend_fields["starts_stream"] = "false";
    record.backend_fields["opens_control_panel"] = "false";
    record.backend_fields["keep_alive_format"] = "valid-dop-silence";
    record.backend_fields["exact_carrier_required"] = "true";
    record.backend_fields["pcm_carrier_sample_type"] =
        ToString(format.sample_type);
    if (format.dsd_rate_multiplier) {
      record.backend_fields["dop_dsd_rate_multiplier"] =
          std::to_string(*format.dsd_rate_multiplier);
    }
    snapshot.probes.push_back(std::move(record));
  }
  if (!probe_result.supported_formats.empty()) {
    return;
  }

  CapabilityProbeRecord record;
  record.kind = CapabilityProbeKind::kFormatSupport;
  record.support = CapabilitySupport::kFailed;
  record.requested_format = probe_result.requested;
  record.detail = probe_result.rejection_reasons.empty()
      ? "ASIO DoP carrier probe did not return a supported format"
      : probe_result.rejection_reasons.front();
  record.backend_fields["api"] = "ASIO DoP carrier query";
  record.backend_fields["creates_buffers"] = "false";
  record.backend_fields["starts_stream"] = "false";
  record.backend_fields["opens_control_panel"] = "false";
  record.backend_fields["keep_alive_format"] = "valid-dop-silence";
  record.backend_fields["exact_carrier_required"] = "true";
  snapshot.probes.push_back(std::move(record));
}

void AddAsioNativeDsdProbeRecords(DeviceCapabilitySnapshot& snapshot,
                                  const FormatProbeResult& probe_result) {
  for (const auto& format : probe_result.supported_formats) {
    CapabilityProbeRecord record;
    record.kind = CapabilityProbeKind::kFormatSupport;
    record.support = CapabilitySupport::kSupported;
    record.requested_format = probe_result.requested;
    record.accepted_format = format;
    record.detail = "ASIO native DSD format accepted for selected driver";
    record.backend_fields["api"] = "ASIO native DSD query";
    record.backend_fields["starts_stream"] = "false";
    record.backend_fields["opens_control_panel"] = "false";
    record.backend_fields["keep_alive_format"] = "valid-dsd-idle";
    snapshot.probes.push_back(std::move(record));
  }
  if (!probe_result.supported_formats.empty()) {
    return;
  }

  CapabilityProbeRecord record;
  record.kind = CapabilityProbeKind::kFormatSupport;
  record.support = CapabilitySupport::kFailed;
  record.requested_format = probe_result.requested;
  record.detail = probe_result.rejection_reasons.empty()
      ? "ASIO native DSD probe did not return a supported format"
      : probe_result.rejection_reasons.front();
  record.backend_fields["api"] = "ASIO native DSD query";
  record.backend_fields["starts_stream"] = "false";
  record.backend_fields["opens_control_panel"] = "false";
  record.backend_fields["keep_alive_format"] = "valid-dsd-idle";
  snapshot.probes.push_back(std::move(record));
}

DeviceCapabilitySnapshot ProbeAsioForMatrix(
    const DeviceInfo& selected_device,
    const std::vector<FormatDescriptor>& rows,
    const std::vector<std::uint32_t>& sample_rate_columns,
    const DiagnosticUiSettings& settings) {
  auto snapshot = MakeDiscoveredDeviceSnapshot(
      MatrixDeviceForBackend(selected_device, BackendApi::kAsio),
      DeviceAvailability::kActive);
  const auto candidates =
      MatrixProbeCandidatesForBackend(rows,
                                      sample_rate_columns,
                                      BackendApi::kAsio);

  if (MatrixRowsContainSignal(rows, SignalMode::kPcm)) {
    AsioPcmBackend backend;
    const auto probe_result = backend.probeFormats(selected_device);
    AddAsioPcmProbeRecords(snapshot, probe_result);
    AddUnsupportedAsioPcmMatrixRows(snapshot, probe_result, candidates);
  }

  if (MatrixRowsContainSignal(rows, SignalMode::kDop)) {
    AsioPcmBackend backend;
    DopConfig requested_dop;
    requested_dop.dsd_rate_multiplier = settings.requested_dsd_rate_multiplier;
    requested_dop.channel_count = settings.requested_channel_count;
    if (settings.requested_sample_type == SampleType::kDsd1BitMsbFirst) {
      requested_dop.dsd_byte_order = SampleType::kDsd1BitMsbFirst;
    }
    AddAsioDopProbeRecords(snapshot,
                           backend.probeDopFormats(selected_device,
                                                   requested_dop));
  }

  if (MatrixRowsContainSignal(rows, SignalMode::kAsioNativeDsd)) {
    AsioNativeDsdBackend backend;
    NativeDsdConfig requested_dsd;
    requested_dsd.dsd_rate_multiplier = settings.requested_dsd_rate_multiplier;
    requested_dsd.channel_count = settings.requested_channel_count;
    if (IsSupportedNativeDsdSampleType(settings.requested_sample_type)) {
      requested_dsd.sample_type = settings.requested_sample_type;
    }
    AddAsioNativeDsdProbeRecords(snapshot,
                                 backend.probeFormats(selected_device,
                                                      requested_dsd));
  }

  snapshot.backend_fields["api"] = "ASIO matrix capability scan";
  snapshot.backend_fields["starts_stream"] = "false";
  snapshot.backend_fields["opens_control_panel"] = "false";
  snapshot.backend_fields["bounded_asio_queries"] = "true";
  return snapshot;
}

std::vector<DeviceCapabilitySnapshot> ProbeMatrixCapabilities(
    const DeviceInfo& selected_device,
    const std::vector<FormatDescriptor>& rows,
    const std::vector<std::uint32_t>& sample_rate_columns,
    BackendApi target_backend,
    const DiagnosticUiSettings& settings) {
  std::vector<DeviceCapabilitySnapshot> snapshots;
  for (const auto backend : std::vector<BackendApi>{target_backend}) {
    if (!CanMapSelectedDeviceToBackend(selected_device, backend)) {
      continue;
    }
    if (backend == BackendApi::kAsio && !IsAsioSdkEnabled()) {
      continue;
    }
    const auto candidates =
        MatrixProbeCandidatesForBackend(rows, sample_rate_columns, backend);
    if (candidates.empty() && backend != BackendApi::kAsio) {
      continue;
    }

    if (backend == BackendApi::kWasapiShared ||
        backend == BackendApi::kWasapiExclusive) {
      WasapiFormatProbeRequest request;
      request.endpoint_id = selected_device.stable_id;
      request.exclusive_mode = backend == BackendApi::kWasapiExclusive;
      request.candidate_formats = candidates;
      snapshots.push_back(ProbeWasapiEndpointFormats(request));
    } else if (backend == BackendApi::kMme) {
      const auto device_id = MmeDeviceIdFromStableId(selected_device.stable_id);
      if (device_id) {
        MmeFormatProbeRequest request;
        request.device_id = *device_id;
        request.candidate_formats = candidates;
        snapshots.push_back(ProbeMmeWaveOutFormats(request));
      }
    } else if (backend == BackendApi::kDirectSound) {
      DirectSoundFormatProbeRequest request;
      request.stable_id = selected_device.stable_id;
      request.candidate_formats = candidates;
      snapshots.push_back(ProbeDirectSoundDeviceFormats(request));
    } else if (backend == BackendApi::kAsio) {
      snapshots.push_back(
          ProbeAsioForMatrix(selected_device,
                             rows,
                             sample_rate_columns,
                             settings));
    } else if (backend == BackendApi::kKernelStreaming) {
      KernelStreamingFormatProbeRequest request;
      request.stable_id = selected_device.stable_id;
      request.candidate_formats = candidates;
      request.create_pin_for_exact_format = false;
      request.detect_wavert_with_pin_probe = true;
      snapshots.push_back(ProbeKernelStreamingPinFormats(request));
    }
  }
  return snapshots;
}

const DeviceCapabilitySnapshot* FindMatrixEvidenceSnapshot(
    const std::vector<DeviceCapabilitySnapshot>& snapshots,
    const std::string& stable_id,
    BackendApi backend) {
  for (const auto& snapshot : snapshots) {
    if (snapshot.device.stable_id == stable_id &&
        snapshot.device.backend == backend) {
      return &snapshot;
    }
  }
  return nullptr;
}

bool IsInUseError(const CapabilityProbeRecord& probe) {
  if (!probe.error) {
    return false;
  }
  return probe.error->symbol.find("DEVICE_IN_USE") != std::string::npos ||
         probe.error->message.find("already in use") != std::string::npos ||
         probe.error->message.find("in use") != std::string::npos;
}

bool IsBackendFormatCombinationApplicable(BackendApi backend,
                                          const FormatDescriptor& format) {
  if (format.signal_mode == SignalMode::kDop) {
    return backend == BackendApi::kWasapiExclusive ||
           backend == BackendApi::kKernelStreaming ||
           backend == BackendApi::kAsio;
  }
  if (format.signal_mode == SignalMode::kAsioNativeDsd) {
    return backend == BackendApi::kAsio;
  }
  return true;
}

bool ProbeAcceptedFormatMatchesCell(const CapabilityProbeRecord& probe,
                                    const FormatDescriptor& row_format) {
  return probe.accepted_format &&
         SameFormat(*probe.accepted_format, row_format);
}

bool ProbeRequestedFormatMatchesCell(const CapabilityProbeRecord& probe,
                                     const FormatDescriptor& row_format) {
  return probe.requested_format &&
         SameFormat(*probe.requested_format, row_format);
}

bool IsPlayableMatrixProbe(BackendApi backend,
                           const CapabilityProbeRecord& probe) {
  return probe.kind == CapabilityProbeKind::kFormatSupport &&
         probe.accepted_format &&
         !IsMixFormatProbe(probe) &&
         IsPlayableAcceptedFormatForBackend(backend,
                                            *probe.accepted_format,
                                            probe);
}

int MatrixProbePriority(BackendApi backend,
                        const FormatDescriptor& row_format,
                        const CapabilityProbeRecord& probe) {
  if (probe.kind != CapabilityProbeKind::kFormatSupport) {
    return -1;
  }
  if (IsMixFormatProbe(probe) &&
      ProbeAcceptedFormatMatchesCell(probe, row_format)) {
    return 60;
  }
  if (IsPlayableMatrixProbe(backend, probe) &&
      ProbeAcceptedFormatMatchesCell(probe, row_format)) {
    return probe.support == CapabilitySupport::kSupported ? 100 : 90;
  }
  if (probe.support == CapabilitySupport::kSupported &&
      ProbeAcceptedFormatMatchesCell(probe, row_format)) {
    return 80;
  }
  if (probe.support == CapabilitySupport::kClosestMatch &&
      ProbeAcceptedFormatMatchesCell(probe, row_format)) {
    return 70;
  }
  if (probe.support == CapabilitySupport::kClosestMatch &&
      ProbeRequestedFormatMatchesCell(probe, row_format)) {
    return 55;
  }
  if ((probe.support == CapabilitySupport::kUnsupported ||
       probe.support == CapabilitySupport::kFailed) &&
      ProbeRequestedFormatMatchesCell(probe, row_format)) {
    return probe.support == CapabilitySupport::kUnsupported ? 50 : 40;
  }
  return -1;
}

CapabilityCellStatus ProbeStatusForMatrixCell(
    BackendApi backend,
    const FormatDescriptor& row_format,
    const CapabilityProbeRecord& probe) {
  if (IsMixFormatProbe(probe)) {
    return CapabilityCellStatus::kReferenceInfo;
  }
  if (backend == BackendApi::kKernelStreaming &&
      probe.support == CapabilitySupport::kSupported &&
      probe.accepted_format &&
      SameFormat(*probe.accepted_format, row_format) &&
      IsKernelStreamingPlaybackFormat(*probe.accepted_format)) {
    if (IsKernelStreamingPlaybackUnimplementedModel(probe)) {
      return CapabilityCellStatus::kWarning;
    }
    const auto level = KernelStreamingProbeResultLevel(probe);
    if (level == "start_verified") {
      return CapabilityCellStatus::kStartVerified;
    }
    if (level == "pin_create_verified") {
      return CapabilityCellStatus::kPinCreateVerified;
    }
    return CapabilityCellStatus::kDataRangeMatch;
  }
  if (probe.support == CapabilitySupport::kSupported &&
      probe.accepted_format) {
    return SameFormat(*probe.accepted_format, row_format) &&
                   IsPlayableAcceptedFormatForBackend(
                       backend,
                       *probe.accepted_format,
                       probe)
        ? CapabilityCellStatus::kAvailable
        : CapabilityCellStatus::kUnsupported;
  }
  if (probe.support == CapabilitySupport::kClosestMatch) {
    return probe.accepted_format &&
           SameFormat(*probe.accepted_format, row_format) &&
           IsPlayableAcceptedFormatForBackend(
               backend,
               *probe.accepted_format,
               probe)
        ? CapabilityCellStatus::kAvailable
        : CapabilityCellStatus::kUnsupported;
  }
  if (probe.support == CapabilitySupport::kUnsupported) {
    return CapabilityCellStatus::kUnsupported;
  }
  if (probe.support == CapabilitySupport::kFailed) {
    return IsInUseError(probe)
        ? CapabilityCellStatus::kInUse
        : CapabilityCellStatus::kError;
  }
  if (!IsBackendFormatCombinationApplicable(backend, row_format)) {
    return CapabilityCellStatus::kNotApplicable;
  }
  return CapabilityCellStatus::kUnchecked;
}

AcceptedFormatSelectionKind MatrixSelectionKindForCell(
    const CapabilityCell& cell) {
  return cell.selection_kind;
}

bool CapabilityStatusCanCreateTestCondition(CapabilityCellStatus status) {
  return status == CapabilityCellStatus::kAvailable ||
         status == CapabilityCellStatus::kDataRangeMatch ||
         status == CapabilityCellStatus::kPinCreateVerified ||
         status == CapabilityCellStatus::kStartVerified;
}

void ApplyFormatToSettings(FormatDescriptor format,
                           BackendApi backend,
                           DiagnosticUiSettings& settings) {
  settings.requested_backend = backend;
  settings.requested_signal = format.signal_mode;
  settings.requested_sample_rate_hz = format.sample_rate_hz;
  settings.requested_sample_type = format.sample_type;
  settings.requested_valid_bits = format.valid_bits_per_sample;
  settings.requested_container_bits = format.container_bits_per_sample;
  settings.requested_channel_count = format.channels.channel_count;
  settings.requested_channel_mask = format.channels.channel_mask;
  if (format.dsd_rate_multiplier) {
    settings.requested_dsd_rate_multiplier = *format.dsd_rate_multiplier;
  }
}

bool LooksLikeKernelStreamingReleaseTimeout(
    std::string_view last_backend_error_summary) {
  return last_backend_error_summary.find(
             "APTT_KS_RENDER_THREAD_JOIN_TIMEOUT") != std::string_view::npos ||
         last_backend_error_summary.find("41005") != std::string_view::npos ||
         last_backend_error_summary.find(
             "\x4B\x53\xE6\x9B\xB8\xE3\x81\x8D\xE8\xBE\xBC\xE3\x81\xBF"
             "\xE3\x82\xB9\xE3\x83\xAC\xE3\x83\x83\xE3\x83\x89") !=
             std::string_view::npos;
}

}  // namespace

AppCloseGuardDecision EvaluateAppCloseGuard(
    std::optional<BackendApi> active_backend,
    std::optional<DeviceLifecycleState> lifecycle_state,
    std::string_view last_backend_error_summary) {
  AppCloseGuardDecision decision;
  if (!active_backend) {
    return decision;
  }

  decision.should_block_quit = true;
  const bool ks_release_timeout =
      *active_backend == BackendApi::kKernelStreaming &&
      lifecycle_state &&
      *lifecycle_state == DeviceLifecycleState::kFaulted &&
      LooksLikeKernelStreamingReleaseTimeout(last_backend_error_summary);
  decision.has_kernel_streaming_release_timeout_warning = ks_release_timeout;
  decision.japanese_message = ks_release_timeout
      ? kCloseGuardKsReleaseTimeoutMessageJapanese
      : kCloseGuardActiveBackendMessageJapanese;
  decision.english_message = ks_release_timeout
      ? kCloseGuardKsReleaseTimeoutMessageEnglish
      : kCloseGuardActiveBackendMessageEnglish;
  return decision;
}

std::optional<std::string> PlaybackCompletionStatusText(
    BackendApi backend,
    DeviceLifecycleState state) {
  if (state == DeviceLifecycleState::kRunningSilence) {
    return std::string(ToString(backend)) +
           " signal stopped; keep-alive stream active";
  }
  if (state == DeviceLifecycleState::kHeldOpen) {
    return std::string(ToString(backend)) +
           " signal stopped; stream held initialized";
  }
  return std::nullopt;
}

const char* ToString(CapabilityCellStatus status) {
  switch (status) {
    case CapabilityCellStatus::kAvailable:
      return "available";
    case CapabilityCellStatus::kDataRangeMatch:
      return "data_range_match";
    case CapabilityCellStatus::kPinCreateVerified:
      return "pin_create_verified";
    case CapabilityCellStatus::kStartVerified:
      return "start_verified";
    case CapabilityCellStatus::kUnsupported:
      return "unsupported";
    case CapabilityCellStatus::kUnchecked:
      return "unchecked";
    case CapabilityCellStatus::kInUse:
      return "in use";
    case CapabilityCellStatus::kReferenceInfo:
      return "reference";
    case CapabilityCellStatus::kWarning:
      return "warning";
    case CapabilityCellStatus::kError:
      return "error";
    case CapabilityCellStatus::kNotApplicable:
      return "not applicable";
  }
  return "unknown";
}

void DiagnosticUiState::UpdateSettings(DiagnosticUiSettings settings) {
  if (settings.requested_sample_rate_hz == 0) {
    settings.requested_sample_rate_hz = 48000;
  }
  if (settings.requested_channel_count == 0) {
    settings.requested_channel_count = 1;
  }
  if (settings.requested_valid_bits == 0) {
    settings.requested_valid_bits = 16;
  }
  if (settings.requested_container_bits < settings.requested_valid_bits) {
    settings.requested_container_bits = settings.requested_valid_bits;
  }
  if (settings.requested_dsd_rate_multiplier != 64 &&
      settings.requested_dsd_rate_multiplier != 128 &&
      settings.requested_dsd_rate_multiplier != 256 &&
      settings.requested_dsd_rate_multiplier != 512 &&
      settings.requested_dsd_rate_multiplier != 1024 &&
      settings.requested_dsd_rate_multiplier != 2048) {
    settings.requested_dsd_rate_multiplier = 64;
  }
  if (settings.frequency_hz <= 0.0) {
    settings.frequency_hz = 1000.0;
  }
  if (settings.amplitude_dbfs > 0.0) {
    settings.amplitude_dbfs = 0.0;
  }
  if (settings.amplitude_dbfs < -144.0) {
    settings.amplitude_dbfs = -144.0;
  }
  if (!settings.continuous && settings.duration_ms == 0) {
    settings.duration_ms = 1;
  }
  if (settings.callback_trace_limit == 0) {
    settings.callback_trace_limit = 1;
  }
  if (settings.periodic_summary_interval_ms == 0) {
    settings.periodic_summary_interval_ms = 1000;
  }
  settings.mme_buffer_count =
      std::clamp<std::uint32_t>(settings.mme_buffer_count, 2, 64);
  settings.mme_buffer_duration_ms =
      std::clamp<std::uint32_t>(settings.mme_buffer_duration_ms, 1, 60000);
  settings.directsound_secondary_buffer_duration_ms =
      std::clamp<std::uint32_t>(
          settings.directsound_secondary_buffer_duration_ms,
          50,
          60000);
  settings.directsound_write_chunk_ms =
      std::clamp<std::uint32_t>(settings.directsound_write_chunk_ms, 1, 60000);
  settings.directsound_cursor_poll_interval_ms = std::clamp<std::uint32_t>(
      settings.directsound_cursor_poll_interval_ms,
      1,
      1000);
  if (settings.directsound_write_chunk_ms >
      settings.directsound_secondary_buffer_duration_ms / 2) {
    settings.directsound_write_chunk_ms =
        std::max<std::uint32_t>(
            1,
            settings.directsound_secondary_buffer_duration_ms / 2);
  }
  settings.wasapi_shared_buffer_duration_ms = std::clamp<std::uint32_t>(
      settings.wasapi_shared_buffer_duration_ms,
      1,
      60000);
  settings.wasapi_shared_render_poll_interval_ms = std::clamp<std::uint32_t>(
      settings.wasapi_shared_render_poll_interval_ms,
      1,
      1000);
  settings.wasapi_exclusive_buffer_duration_ms = std::clamp<std::uint32_t>(
      settings.wasapi_exclusive_buffer_duration_ms,
      1,
      5000);
  settings.wasapi_exclusive_periodicity_ms = std::clamp<std::uint32_t>(
      settings.wasapi_exclusive_periodicity_ms,
      0,
      settings.wasapi_exclusive_buffer_duration_ms);
  settings.wasapi_exclusive_render_poll_interval_ms = std::clamp<std::uint32_t>(
      settings.wasapi_exclusive_render_poll_interval_ms,
      1,
      1000);
  settings.wasapi_exclusive_event_timeout_ms = std::clamp<std::uint32_t>(
      settings.wasapi_exclusive_event_timeout_ms,
      1,
      60000);
  if (settings.wasapi_exclusive_event_callback_enabled) {
    settings.wasapi_exclusive_periodicity_ms =
        settings.wasapi_exclusive_buffer_duration_ms;
  }
  if (settings.audio_thread_mmcss_task_name != "Audio") {
    settings.audio_thread_mmcss_task_name = "Pro Audio";
  }
  settings.audio_thread_mmcss_priority =
      std::clamp<std::int32_t>(settings.audio_thread_mmcss_priority, -1, 2);
  settings.high_load_render_delay_ms = std::clamp<std::uint32_t>(
      settings.high_load_render_delay_ms,
      1,
      500);
  settings.high_load_delay_every_callbacks = std::clamp<std::uint32_t>(
      settings.high_load_delay_every_callbacks,
      1,
      1000);
  if (!settings.high_load_diagnostics_enabled) {
    settings.high_load_risk_acknowledged = false;
  }

  if (HasAnyActiveBackend()) {
    if (IsOnlyUnsafeReleaseAcknowledgementDifferent(settings_, settings)) {
      settings_.expert_unsafe_release_ack = settings.expert_unsafe_release_ack;
      status_text_ = settings_.expert_unsafe_release_ack
          ? "release acknowledgement enabled"
          : "release acknowledgement cleared";
      log_lines_.push_back(
          settings_.expert_unsafe_release_ack
              ? "release acknowledgement updated while backend active; held-device release can proceed after signal stop"
              : "release acknowledgement cleared while backend active");
      return;
    }
    last_run_ok_ = false;
    status_text_ = "active backend locked";
    log_lines_.push_back(
        "settings change blocked: " +
        std::string(kActiveBackendInterlockReason));
    return;
  }

  const bool format_affecting_change =
      IsFormatChangingSettingDifferent(settings_, settings);
  const bool run_config_change =
      IsRunConfigSettingDifferent(settings_, settings);
  const bool requested_backend_changed =
      settings_.requested_backend != settings.requested_backend;
  settings_ = std::move(settings);
  if (requested_backend_changed) {
    ResetAcceptedFormatSelection();
    ClearProbeRows();
    selected_device_.reset();
    status_text_ = "backend changed; device cleared";
    log_lines_.push_back(
        "requested backend changed; reload the selected API before choosing a device");
    MarkDeviceCapabilityMatrixStale("requested backend changed");
  }
  if (format_affecting_change) {
    ++format_revision_;
    MarkDeviceCapabilityMatrixStale("format settings changed");
    if (selected_playback_format_) {
      last_run_ok_ = false;
      status_text_ = "format settings changed";
      log_lines_.push_back(
          "format settings changed after the last probe; probe again before starting");
    }
  } else if (run_config_change) {
    ++run_config_revision_;
    if (selected_playback_format_) {
      status_text_ = "playback settings changed";
      log_lines_.push_back(
          "playback settings changed after the last probe; reprobe is not required");
    }
  }
}

bool DiagnosticUiState::accepted_format_is_stale() const {
  return selected_playback_format_.has_value() &&
         (!accepted_format_settings_revision_ ||
          *accepted_format_settings_revision_ != format_revision_);
}

bool DiagnosticUiState::selected_test_condition_is_stale() const {
  if (!selected_test_condition_) {
    return false;
  }
  if (!selected_device_ || !selected_playback_format_ ||
      !selected_playback_backend_) {
    return true;
  }
  const auto& condition = *selected_test_condition_;
  if (condition.target_device.stable_id != selected_device_->stable_id ||
      condition.backend != selected_device_->backend ||
      condition.backend != *selected_playback_backend_ ||
      !SameFormat(condition.accepted_playback_format,
                  *selected_playback_format_)) {
    return true;
  }
  if (accepted_format_is_stale()) {
    return true;
  }
  if (condition.matrix_scan_revision > 0) {
    if (!device_capability_matrix_ || device_capability_matrix_->stale ||
        device_capability_matrix_->scan_revision !=
            condition.matrix_scan_revision) {
      return true;
    }
  }
  return false;
}

bool DiagnosticUiState::last_probe_rows_are_stale() const {
  return (last_probe_has_format_rows_ || SelectedSnapshotHasFormatProbeRows()) &&
         (!last_probe_format_revision_.has_value() ||
          *last_probe_format_revision_ != format_revision_);
}

std::string DiagnosticUiState::accepted_format_state_text() const {
  if (!selected_playback_format_) {
    return "none";
  }
  if (accepted_format_is_stale()) {
    return "stale - probe again";
  }
  return ToString(accepted_format_selection_kind_);
}

std::string DiagnosticUiState::accepted_format_state_text_japanese() const {
  if (!selected_playback_format_) {
    return "\xE3\x81\xAA\xE3\x81\x97";
  }
  if (accepted_format_is_stale()) {
    return "\xE5\x86\x8D\xE7\xA2\xBA\xE8\xAA\x8D\xE3\x81\x8C"
           "\xE5\xBF\x85\xE8\xA6\x81";
  }
  switch (accepted_format_selection_kind_) {
    case AcceptedFormatSelectionKind::kNone:
      return "\xE3\x81\xAA\xE3\x81\x97";
    case AcceptedFormatSelectionKind::kRequestedExact:
      return "\xE5\xAF\xBE\xE5\xBF\x9C\xE3\x82\xBB\xE3\x83\xAB"
             "\xE3\x82\x92\xE9\x81\xB8\xE6\x8A\x9E";
    case AcceptedFormatSelectionKind::kUserFallback:
      return "\xE4\xBB\xA3\xE6\x9B\xBF\xE3\x83\x95\xE3\x82\xA9"
             "\xE3\x83\xBC\xE3\x83\x9E\xE3\x83\x83\xE3\x83\x88"
             "\xE3\x82\x92\xE9\x81\xB8\xE6\x8A\x9E";
    case AcceptedFormatSelectionKind::kUserMixFormat:
      return "\xE3\x83\x9F\xE3\x83\x83\xE3\x82\xAF\xE3\x82\xB9"
             "\xE5\xBD\xA2\xE5\xBC\x8F\xE3\x82\x92\xE9\x81\xB8"
             "\xE6\x8A\x9E";
    case AcceptedFormatSelectionKind::kUserClosestMatch:
      return "\xE8\xBF\x91\xE4\xBC\xBC\xE3\x83\x95\xE3\x82\xA9"
             "\xE3\x83\xBC\xE3\x83\x9E\xE3\x83\x83\xE3\x83\x88"
             "\xE3\x82\x92\xE9\x81\xB8\xE6\x8A\x9E";
  }
  return "\xE3\x81\xAA\xE3\x81\x97";
}

bool DiagnosticUiState::HasAnyActiveBackend() const {
  return injected_active_backend_for_testing_.has_value() ||
         wasapi_shared_backend_ != nullptr ||
         wasapi_exclusive_backend_ != nullptr ||
         mme_backend_ != nullptr ||
         directsound_backend_ != nullptr ||
         kernel_streaming_backend_ != nullptr ||
         asio_backend_ != nullptr ||
         asio_native_dsd_backend_ != nullptr;
}

std::optional<BackendApi> DiagnosticUiState::active_backend_api() const {
  if (wasapi_shared_backend_) {
    return BackendApi::kWasapiShared;
  }
  if (wasapi_exclusive_backend_) {
    return BackendApi::kWasapiExclusive;
  }
  if (mme_backend_) {
    return BackendApi::kMme;
  }
  if (directsound_backend_) {
    return BackendApi::kDirectSound;
  }
  if (kernel_streaming_backend_) {
    return BackendApi::kKernelStreaming;
  }
  if (asio_backend_) {
    return BackendApi::kAsio;
  }
  if (asio_native_dsd_backend_) {
    return BackendApi::kAsio;
  }
  if (injected_active_backend_for_testing_) {
    return injected_active_backend_for_testing_;
  }
  return std::nullopt;
}

std::optional<DeviceLifecycleState>
DiagnosticUiState::active_backend_lifecycle_state() const {
  if (wasapi_shared_backend_) {
    return wasapi_shared_backend_->lifecycle_state();
  }
  if (wasapi_exclusive_backend_) {
    return wasapi_exclusive_backend_->lifecycle_state();
  }
  if (mme_backend_) {
    return mme_backend_->lifecycle_state();
  }
  if (directsound_backend_) {
    return directsound_backend_->lifecycle_state();
  }
  if (kernel_streaming_backend_) {
    return kernel_streaming_backend_->lifecycle_state();
  }
  if (asio_backend_) {
    return asio_backend_->lifecycle_state();
  }
  if (asio_native_dsd_backend_) {
    return asio_native_dsd_backend_->lifecycle_state();
  }
  if (injected_active_backend_for_testing_) {
    return DeviceLifecycleState::kRunningSignal;
  }
  return std::nullopt;
}

AppCloseGuardDecision DiagnosticUiState::app_close_guard_decision() const {
  return EvaluateAppCloseGuard(active_backend_api(),
                               active_backend_lifecycle_state(),
                               last_backend_error_summary_);
}

void DiagnosticUiState::InjectActiveBackendForTesting(BackendApi backend) {
  injected_active_backend_for_testing_ = backend;
}

void DiagnosticUiState::ClearInjectedActiveBackendForTesting() {
  injected_active_backend_for_testing_.reset();
}

FormatDescriptor DiagnosticUiState::BuildRequestedPcmFormatFromSettings() const {
  FormatDescriptor descriptor;
  descriptor.signal_mode = SignalMode::kPcm;
  descriptor.sample_rate_hz = settings_.requested_sample_rate_hz;
  descriptor.sample_type = IsPcmSampleType(settings_.requested_sample_type)
      ? settings_.requested_sample_type
      : SampleType::kFloat32;
  descriptor.valid_bits_per_sample = settings_.requested_valid_bits;
  descriptor.container_bits_per_sample = settings_.requested_container_bits;
  if (!IsPcmSampleType(settings_.requested_sample_type)) {
    descriptor.valid_bits_per_sample = 32;
    descriptor.container_bits_per_sample = 32;
  }
  descriptor.channels.channel_count = settings_.requested_channel_count;
  descriptor.channels.channel_mask = settings_.requested_channel_mask;
  return descriptor;
}

FormatDescriptor
DiagnosticUiState::BuildRequestedDopCarrierFromSettings() const {
  DopConfig config;
  config.dsd_rate_multiplier = settings_.requested_dsd_rate_multiplier;
  config.channel_count = settings_.requested_channel_count;
  if (settings_.requested_sample_type == SampleType::kDsd1BitMsbFirst) {
    config.dsd_byte_order = SampleType::kDsd1BitMsbFirst;
  } else {
    config.dsd_byte_order = SampleType::kDsd1BitLsbFirst;
  }
  return MakeDopCarrierFormat(config);
}

FormatDescriptor
DiagnosticUiState::BuildRequestedNativeDsdFormatFromSettings() const {
  NativeDsdConfig config;
  config.dsd_rate_multiplier = settings_.requested_dsd_rate_multiplier;
  config.channel_count = settings_.requested_channel_count;
  if (IsSupportedNativeDsdSampleType(settings_.requested_sample_type)) {
    config.sample_type = settings_.requested_sample_type;
  }
  return MakeNativeDsdFormat(config);
}

FormatDescriptor DiagnosticUiState::requested_format_from_settings() const {
  if (settings_.requested_signal == SignalMode::kDop) {
    return BuildRequestedDopCarrierFromSettings();
  }
  if (settings_.requested_signal == SignalMode::kAsioNativeDsd) {
    return BuildRequestedNativeDsdFormatFromSettings();
  }
  return BuildRequestedPcmFormatFromSettings();
}

void DiagnosticUiState::Tick() {
  if (directsound_backend_) {
    AppendDirectSoundEvents();
    stats_ = directsound_backend_->getRealtimeStats();
    const auto events = directsound_backend_->diagnostic_events();
    RecordLastEvents(events);
    UpdatePcmSummaryFromEvents(BackendApi::kDirectSound, events, stats_);
    UpdatePlaybackCompletionStatus(
        BackendApi::kDirectSound,
        directsound_backend_->lifecycle_state(),
        stats_);
    UpdateLastBackendError(directsound_backend_->getLastError(),
                           "DirectSound");
  }
  if (mme_backend_) {
    AppendMmeEvents();
    stats_ = mme_backend_->getRealtimeStats();
    const auto events = mme_backend_->diagnostic_events();
    RecordLastEvents(events);
    UpdatePcmSummaryFromEvents(BackendApi::kMme, events, stats_);
    UpdatePlaybackCompletionStatus(
        BackendApi::kMme,
        mme_backend_->lifecycle_state(),
        stats_);
    UpdateLastBackendError(mme_backend_->getLastError(), "MME");
  }
  if (wasapi_shared_backend_) {
    AppendWasapiSharedEvents();
    stats_ = wasapi_shared_backend_->getRealtimeStats();
    const auto events = wasapi_shared_backend_->diagnostic_events();
    RecordLastEvents(events);
    UpdatePcmSummaryFromEvents(BackendApi::kWasapiShared, events, stats_);
    UpdatePlaybackCompletionStatus(
        BackendApi::kWasapiShared,
        wasapi_shared_backend_->lifecycle_state(),
        stats_);
    UpdateLastBackendError(wasapi_shared_backend_->getLastError(),
                           "WASAPI shared");
  }
  if (wasapi_exclusive_backend_) {
    AppendWasapiExclusiveEvents();
    stats_ = wasapi_exclusive_backend_->getRealtimeStats();
    const auto events = wasapi_exclusive_backend_->diagnostic_events();
    RecordLastEvents(events);
    UpdatePcmSummaryFromEvents(BackendApi::kWasapiExclusive, events, stats_);
    UpdatePlaybackCompletionStatus(
        BackendApi::kWasapiExclusive,
        wasapi_exclusive_backend_->lifecycle_state(),
        stats_);
    UpdateLastBackendError(wasapi_exclusive_backend_->getLastError(),
                           "WASAPI exclusive");
  }
  if (kernel_streaming_backend_) {
    AppendKernelStreamingEvents();
    stats_ = kernel_streaming_backend_->getRealtimeStats();
    const auto events = kernel_streaming_backend_->diagnostic_events();
    RecordLastEvents(events);
    UpdatePcmSummaryFromEvents(BackendApi::kKernelStreaming, events, stats_);
    UpdatePlaybackCompletionStatus(
        BackendApi::kKernelStreaming,
        kernel_streaming_backend_->lifecycle_state(),
        stats_);
    UpdateLastBackendError(kernel_streaming_backend_->getLastError(),
                           "Kernel Streaming");
  }
  if (asio_backend_) {
    AppendAsioEvents();
    stats_ = asio_backend_->getRealtimeStats();
    const auto events = asio_backend_->diagnostic_events();
    RecordLastEvents(events);
    UpdatePcmSummaryFromEvents(BackendApi::kAsio, events, stats_);
    UpdatePlaybackCompletionStatus(
        BackendApi::kAsio,
        asio_backend_->lifecycle_state(),
        stats_);
    UpdateLastBackendError(asio_backend_->getLastError(), "ASIO");
  }
  if (asio_native_dsd_backend_) {
    AppendAsioNativeDsdEvents();
    stats_ = asio_native_dsd_backend_->getRealtimeStats();
    const auto events = asio_native_dsd_backend_->diagnostic_events();
    RecordLastEvents(events);
    UpdatePlaybackCompletionStatus(
        BackendApi::kAsio,
        asio_native_dsd_backend_->lifecycle_state(),
        stats_);
    UpdateLastBackendError(asio_native_dsd_backend_->getLastError(),
                           "ASIO native DSD");
  }
}

std::vector<std::string> DiagnosticUiState::settings_warnings() const {
  std::vector<std::string> warnings;
  const bool known_problem =
      settings_.manual_known_problem_device ||
      (selected_device_ && selected_device_->is_known_problem_device);
  if (known_problem && IsFullReleaseMode(settings_.hold_mode)) {
    warnings.push_back(
        "known-problem device profile is selected; full release is blocked unless explicitly acknowledged");
  }
  if (known_problem && !settings_.keep_alive_stream_enabled) {
    warnings.push_back(
        "known-problem device profile should keep a valid keep-alive stream or hold initialized");
  }
  if (settings_.hold_mode == HoldMode::kImmediateRelease) {
    warnings.push_back(
        "immediate release is a manual diagnostic option and is not a safe default");
  } else if (settings_.hold_mode == HoldMode::kReleaseAfterDrain) {
    warnings.push_back(
        "release after drain can allow USB or ASIO devices to suspend after cooldown");
  }
  if (!settings_.rapid_format_cycle_guard) {
    warnings.push_back(
        "rapid format cycling guard is disabled");
  }
  if (settings_.max_reacquire_attempts > 1) {
    warnings.push_back(
        "reacquire attempts above one must remain cooldown-gated and bounded");
  }
  if (settings_.log_level == DiagnosticLogLevel::kCallbackTrace ||
      settings_.callback_event_logging) {
    warnings.push_back(
        "callback trace logging can be high volume during long runs");
  }
  if (!settings_.left_channel_enabled && !settings_.right_channel_enabled) {
    warnings.push_back("all visible output channels are muted");
  }
  if (settings_.automatic_start_stop_stress_enabled) {
    warnings.push_back(
        "automatic start/stop stress is expert-only and requires cooldown-gated execution");
  }
  if (settings_.automatic_reinitialize_enabled) {
    warnings.push_back(
        "automatic reinitialize loops are expert-only and must remain bounded");
  }
  if (settings_.high_load_diagnostics_enabled) {
    warnings.push_back(
        "high-load diagnostics intentionally delay rendering and can provoke audible dropouts");
  }
  return warnings;
}

void DiagnosticUiState::ApplySettingsToConfig(PlaybackConfig& config) const {
  config.frequency_hz = settings_.frequency_hz;
  config.amplitude_dbfs = settings_.amplitude_dbfs;
  config.duration_ms = settings_.duration_ms;
  config.continuous = settings_.continuous;
  config.fade_in_ms = settings_.fade_in_ms;
  config.fade_out_ms = settings_.fade_out_ms;
  config.silence_preroll_ms = settings_.silence_preroll_ms;
  config.silence_postroll_ms = settings_.silence_postroll_ms;
  config.left_channel_enabled = settings_.left_channel_enabled;
  config.right_channel_enabled = settings_.right_channel_enabled;
  config.invert_right_phase = settings_.invert_right_phase;
  config.right_channel_phase_offset_degrees = settings_.phase_offset_degrees;
  config.hold_mode = settings_.hold_mode;
  if (!settings_.keep_alive_stream_enabled &&
      config.hold_mode == HoldMode::kKeepWarmAfterStop) {
    config.hold_mode = HoldMode::kHoldInitialized;
  }
  config.release_cooldown_ms = settings_.release_cooldown_ms;
  config.reacquire_cooldown_ms = settings_.reacquire_cooldown_ms;
  config.max_reacquire_attempts = settings_.max_reacquire_attempts;
  config.mme_buffer_count = settings_.mme_buffer_count;
  config.mme_buffer_duration_ms = settings_.mme_buffer_duration_ms;
  config.directsound_secondary_buffer_duration_ms =
      settings_.directsound_secondary_buffer_duration_ms;
  config.directsound_write_chunk_ms = settings_.directsound_write_chunk_ms;
  config.directsound_cursor_poll_interval_ms =
      settings_.directsound_cursor_poll_interval_ms;
  config.wasapi_shared_buffer_duration_ms =
      settings_.wasapi_shared_buffer_duration_ms;
  config.wasapi_shared_render_poll_interval_ms =
      settings_.wasapi_shared_render_poll_interval_ms;
  config.wasapi_exclusive_buffer_duration_ms =
      settings_.wasapi_exclusive_buffer_duration_ms;
  config.wasapi_exclusive_periodicity_ms =
      settings_.wasapi_exclusive_periodicity_ms;
  config.wasapi_exclusive_render_poll_interval_ms =
      settings_.wasapi_exclusive_render_poll_interval_ms;
  config.wasapi_exclusive_event_callback_enabled =
      settings_.wasapi_exclusive_event_callback_enabled;
  config.wasapi_exclusive_alignment_retry_enabled =
      settings_.wasapi_exclusive_alignment_retry_enabled;
  config.wasapi_exclusive_event_timeout_ms =
      settings_.wasapi_exclusive_event_timeout_ms;
  config.audio_thread_mmcss_enabled = settings_.audio_thread_mmcss_enabled;
  config.audio_thread_mmcss_task_name = settings_.audio_thread_mmcss_task_name;
  config.audio_thread_mmcss_priority = settings_.audio_thread_mmcss_priority;
  config.asio_use_output_ready_if_supported =
      settings_.asio_use_output_ready_if_supported;
  config.high_load_diagnostics_enabled =
      settings_.high_load_diagnostics_enabled;
  config.high_load_risk_acknowledged =
      settings_.high_load_diagnostics_enabled &&
      settings_.high_load_risk_acknowledged;
  config.high_load_render_delay_ms =
      settings_.high_load_diagnostics_enabled
          ? settings_.high_load_render_delay_ms
          : 0;
  config.high_load_delay_every_callbacks =
      settings_.high_load_delay_every_callbacks;
}

bool DiagnosticUiState::EnsureStartSafety(const char* action_label) {
  if (HasAnyActiveBackend()) {
    last_run_ok_ = false;
    status_text_ = "active backend locked";
    std::ostringstream line;
    line << action_label << " blocked: " << kActiveBackendInterlockReason;
    log_lines_.push_back(line.str());
    return false;
  }
  if (accepted_format_is_stale()) {
    last_run_ok_ = false;
    status_text_ = "format probe stale";
    std::ostringstream line;
    line << action_label
         << " blocked: Format settings changed after the last probe. Probe again before starting.";
    log_lines_.push_back(line.str());
    return false;
  }
  if (!selected_test_condition_) {
    last_run_ok_ = false;
    status_text_ = "test condition not selected";
    std::ostringstream line;
    line << action_label
         << " blocked: select a non-stale test condition from the capability matrix before starting";
    log_lines_.push_back(line.str());
    return false;
  }
  if (selected_test_condition_is_stale()) {
    last_run_ok_ = false;
    status_text_ = "test condition stale";
    std::ostringstream line;
    line << action_label
         << " blocked: selected test condition is stale; rebuild the matrix or select a current cell";
    log_lines_.push_back(line.str());
    return false;
  }
  if (!selected_device_ ||
      !DeviceMatchesRequestedBackend(*selected_device_,
                                     settings_.requested_backend)) {
    last_run_ok_ = false;
    status_text_ = "backend mismatch";
    std::ostringstream line;
    line << action_label
         << " blocked: selected device does not belong to the current target API";
    log_lines_.push_back(line.str());
    return false;
  }
  const bool known_problem =
      settings_.manual_known_problem_device ||
      (selected_device_ && selected_device_->is_known_problem_device);
  if (known_problem && IsFullReleaseMode(settings_.hold_mode) &&
      !settings_.expert_unsafe_release_ack) {
    last_run_ok_ = false;
    status_text_ = "unsafe lifecycle settings";
    std::ostringstream line;
    line << action_label
         << " blocked: known-problem device requires keep-warm/hold-open or explicit unsafe release acknowledgement";
    log_lines_.push_back(line.str());
    return false;
  }
  if (!settings_.left_channel_enabled && !settings_.right_channel_enabled) {
    last_run_ok_ = false;
    status_text_ = "no output channel enabled";
    std::ostringstream line;
    line << action_label << " blocked: at least one output channel must be enabled";
    log_lines_.push_back(line.str());
    return false;
  }
  if (settings_.high_load_diagnostics_enabled &&
      !settings_.high_load_risk_acknowledged) {
    last_run_ok_ = false;
    status_text_ = "high-load acknowledgement required";
    std::ostringstream line;
    line << action_label
         << " blocked: high-load diagnostics require explicit expert acknowledgement";
    log_lines_.push_back(line.str());
    return false;
  }
  return true;
}

bool DiagnosticUiState::RejectIfActive(const char* action_label) {
  if (!HasAnyActiveBackend()) {
    return false;
  }
  last_run_ok_ = false;
  status_text_ = "active backend locked";
  std::ostringstream line;
  line << action_label << " blocked: " << kActiveBackendInterlockReason;
  log_lines_.push_back(line.str());
  return true;
}

void DiagnosticUiState::ResetAcceptedFormatSelection() {
  selected_playback_format_.reset();
  selected_playback_backend_.reset();
  selected_test_condition_.reset();
  accepted_format_settings_revision_.reset();
  accepted_format_selection_kind_ = AcceptedFormatSelectionKind::kNone;
}

void DiagnosticUiState::ClearProbeRows() {
  last_format_probe_ = FormatProbeResult{};
  last_probe_format_revision_.reset();
  last_probe_has_format_rows_ = false;
}

void DiagnosticUiState::ClearDeviceCapabilityMatrix() {
  device_capability_matrix_.reset();
  selected_test_condition_.reset();
}

void DiagnosticUiState::MarkDeviceCapabilityMatrixStale(
    std::string_view reason) {
  if (!device_capability_matrix_) {
    selected_test_condition_.reset();
    return;
  }
  device_capability_matrix_->stale = true;
  selected_test_condition_.reset();
  if (!reason.empty()) {
    log_lines_.push_back(
        "capability matrix marked stale: " + std::string(reason));
  }
}

void DiagnosticUiState::MarkProbeRowsFreshForCurrentFormat() {
  last_probe_format_revision_ = format_revision_;
}

bool DiagnosticUiState::SelectedSnapshotHasFormatProbeRows() const {
  if (!selected_device_) {
    return false;
  }
  const auto selected = FindDeviceByStableId(
      discovery_snapshot_,
      selected_device_->stable_id);
  if (!selected) {
    return false;
  }
  for (const auto& probe : selected->probes) {
    if (probe.kind == CapabilityProbeKind::kFormatSupport) {
      return true;
    }
  }
  return false;
}

bool DiagnosticUiState::ProbeRowsAreFreshForCurrentFormat() const {
  return (last_probe_has_format_rows_ || SelectedSnapshotHasFormatProbeRows()) &&
         last_probe_format_revision_.has_value() &&
         *last_probe_format_revision_ == format_revision_;
}

bool DiagnosticUiState::RejectIfProbeRowsStale(const char* action_label) {
  if (!last_probe_rows_are_stale()) {
    return false;
  }
  last_run_ok_ = false;
  status_text_ = "format probe stale";
  std::ostringstream line;
  line << action_label
       << " blocked: format settings changed after this probe; probe again before selecting a row";
  log_lines_.push_back(line.str());
  return true;
}

bool DiagnosticUiState::RejectIfRequestedSignalIsNot(
    SignalMode signal,
    const char* action_label) {
  if (settings_.requested_signal == signal) {
    return false;
  }
  last_run_ok_ = false;
  status_text_ = "signal/backend mismatch";
  std::ostringstream line;
  line << action_label << " blocked: requested signal "
       << ToString(settings_.requested_signal)
       << " is incompatible with this probe";
  log_lines_.push_back(line.str());
  return true;
}

bool DiagnosticUiState::RejectIfRequestedBackendIsNot(
    BackendApi backend,
    const char* action_label) {
  if (settings_.requested_backend == backend) {
    return false;
  }
  last_run_ok_ = false;
  status_text_ = "signal/backend mismatch";
  std::ostringstream line;
  line << action_label << " blocked: requested backend "
       << ToString(settings_.requested_backend)
       << " is incompatible with this probe";
  log_lines_.push_back(line.str());
  return true;
}

bool DiagnosticUiState::RejectIfSelectedDeviceIsNotWasapiEndpoint(
    const char* action_label) {
  if (selected_device_ &&
      IsWasapiEndpointMode(selected_device_->backend)) {
    return false;
  }
  last_run_ok_ = false;
  status_text_ = "WASAPI endpoint not selected";
  std::ostringstream line;
  line << action_label
       << " blocked: selected device is not a WASAPI endpoint";
  log_lines_.push_back(line.str());
  return true;
}

void DiagnosticUiState::AcceptPlaybackFormat(
    FormatDescriptor format,
    BackendApi backend,
    AcceptedFormatSelectionKind kind,
    std::string_view reason) {
  selected_playback_format_ = std::move(format);
  selected_playback_backend_ = backend;
  accepted_format_settings_revision_ = format_revision_;
  accepted_format_selection_kind_ = kind;

  std::ostringstream format_line;
  format_line << "selected accepted format: "
              << selected_playback_format_->sample_rate_hz << " Hz "
              << selected_playback_format_->channels.channel_count << " ch "
              << ToString(selected_playback_format_->sample_type)
              << " signal=" << ToString(selected_playback_format_->signal_mode)
              << " selection=" << ToString(kind);
  if (selected_playback_format_->dsd_rate_multiplier) {
    format_line << " DSD" << *selected_playback_format_->dsd_rate_multiplier;
  }
  format_line << " backend=" << ToString(backend);
  if (!reason.empty()) {
    format_line << " reason=" << reason;
  }
  log_lines_.push_back(format_line.str());
}

void DiagnosticUiState::StoreSelectedTestCondition(
    BackendApi backend,
    FormatDescriptor requested_format,
    FormatDescriptor accepted_format,
    std::uint64_t matrix_scan_revision,
    std::size_t matrix_row,
    std::size_t matrix_column,
    std::string backend_device_id,
    std::string backend_device_name,
    CapabilityCellStatus capability_status,
    std::map<std::string, std::string> raw_backend_fields) {
  if (!selected_device_) {
    selected_test_condition_.reset();
    return;
  }
  SelectedTestCondition condition;
  condition.target_device = *selected_device_;
  condition.backend = backend;
  condition.backend_device_id = std::move(backend_device_id);
  condition.backend_device_name = std::move(backend_device_name);
  condition.requested_format = std::move(requested_format);
  condition.accepted_playback_format = std::move(accepted_format);
  condition.signal_frequency_hz = settings_.frequency_hz;
  condition.signal_amplitude_dbfs = settings_.amplitude_dbfs;
  condition.duration_ms = settings_.duration_ms;
  condition.hold_mode = settings_.hold_mode;
  condition.capability_status = capability_status;
  condition.raw_backend_fields = std::move(raw_backend_fields);
  condition.matrix_scan_revision = matrix_scan_revision;
  condition.matrix_row = matrix_row;
  condition.matrix_column = matrix_column;
  selected_test_condition_ = std::move(condition);
}

void DiagnosticUiState::AutoSelectExactRequestedFormatFromSelectedSnapshot() {
  if (!selected_device_) {
    return;
  }
  if (!ProbeRowsAreFreshForCurrentFormat()) {
    return;
  }
  const auto selected = FindDeviceByStableId(
      discovery_snapshot_,
      selected_device_->stable_id);
  if (!selected) {
    return;
  }

  const auto current_request = requested_format_from_settings();
  const BackendApi acceptance_backend = selected_device_->backend;
  if (acceptance_backend != settings_.requested_backend) {
    return;
  }
  for (const auto& probe : selected->probes) {
    if (probe.kind != CapabilityProbeKind::kFormatSupport ||
        !probe.accepted_format) {
      continue;
    }
    const auto kind = SelectionKindForProbe(probe, current_request);
    if (kind != AcceptedFormatSelectionKind::kRequestedExact) {
      continue;
    }
    const bool snapshot_backend_matches =
        selected->device.backend == acceptance_backend;
    if (!snapshot_backend_matches) {
      continue;
    }
    if (!IsPlayableAcceptedFormatForBackend(acceptance_backend,
                                            *probe.accepted_format,
                                            probe)) {
      continue;
    }
    AcceptPlaybackFormat(*probe.accepted_format,
                         acceptance_backend,
                         kind,
                         "exact playable probe");
    return;
  }
}

void DiagnosticUiState::AppendRequestedSettingsLog(
    const PlaybackConfig& config,
    const char* action_label) {
  last_playback_completion_status_.reset();

  std::ostringstream playback;
  playback << action_label << " requested settings: backend="
           << ToString(config.backend)
           << " signal=" << ToString(config.format.signal_mode)
           << " accepted_rate=" << config.format.sample_rate_hz
           << " accepted_channels=" << config.format.channels.channel_count
           << " frequency_hz=" << config.frequency_hz
           << " amplitude_dbfs=" << config.amplitude_dbfs
           << " duration_ms=" << config.duration_ms
           << " continuous=" << (config.continuous ? "true" : "false")
           << " fade_in_ms=" << config.fade_in_ms
           << " fade_out_ms=" << config.fade_out_ms
           << " preroll_ms=" << config.silence_preroll_ms
           << " postroll_ms=" << config.silence_postroll_ms
           << " left_channel=" << (config.left_channel_enabled ? "on" : "off")
           << " right_channel=" << (config.right_channel_enabled ? "on" : "off")
           << " invert_right=" << (config.invert_right_phase ? "true" : "false")
           << " right_phase_offset_degrees="
           << config.right_channel_phase_offset_degrees
           << " hold_mode=" << ToString(config.hold_mode)
           << " keep_alive=" << (settings_.keep_alive_stream_enabled ? "true" : "false")
           << " release_cooldown_ms=" << config.release_cooldown_ms
           << " reacquire_cooldown_ms=" << config.reacquire_cooldown_ms
         << " max_reacquire_attempts=" << config.max_reacquire_attempts;
  playback << " high_load_mode="
           << (config.high_load_diagnostics_enabled ? "true" : "false")
           << " high_load_mechanism="
           << (config.high_load_diagnostics_enabled
                   ? "bounded_render_callback_delay"
                   : "off")
           << " high_load_delay_ms=" << config.high_load_render_delay_ms
           << " high_load_delay_every_callbacks="
           << config.high_load_delay_every_callbacks;
  log_lines_.push_back(playback.str());

  std::ostringstream expert;
  expert << action_label << " API scheduling settings: requested_backend="
         << ToString(settings_.requested_backend)
         << " requested_signal=" << ToString(settings_.requested_signal)
         << " requested_rate=" << settings_.requested_sample_rate_hz
         << " requested_sample_type=" << ToString(settings_.requested_sample_type)
         << " requested_valid_bits=" << settings_.requested_valid_bits
         << " requested_container_bits=" << settings_.requested_container_bits
         << " requested_channels=" << settings_.requested_channel_count
         << " requested_channel_mask=" << settings_.requested_channel_mask
         << " dsd_rate=DSD" << settings_.requested_dsd_rate_multiplier;
  switch (config.backend) {
    case BackendApi::kMme:
      expert << " mme_buffer_count=" << config.mme_buffer_count
             << " mme_buffer_duration_ms="
             << config.mme_buffer_duration_ms
             << " mme_callback_mode=CALLBACK_EVENT"
             << " audio_thread_mmcss_enabled="
             << (config.audio_thread_mmcss_enabled ? "true" : "false")
             << " audio_thread_mmcss_task=\""
             << config.audio_thread_mmcss_task_name
             << "\" audio_thread_mmcss_priority="
             << config.audio_thread_mmcss_priority;
      break;
    case BackendApi::kDirectSound:
      expert << " directsound_secondary_buffer_ms="
             << config.directsound_secondary_buffer_duration_ms
             << " directsound_write_chunk_ms="
             << config.directsound_write_chunk_ms
             << " directsound_cursor_poll_ms="
             << config.directsound_cursor_poll_interval_ms
             << " directsound_cooperative_level=DSSCL_NORMAL"
             << " audio_thread_mmcss_enabled="
             << (config.audio_thread_mmcss_enabled ? "true" : "false")
             << " audio_thread_mmcss_task=\""
             << config.audio_thread_mmcss_task_name
             << "\" audio_thread_mmcss_priority="
             << config.audio_thread_mmcss_priority;
      break;
    case BackendApi::kWasapiShared:
      expert << " wasapi_shared_buffer_ms="
             << config.wasapi_shared_buffer_duration_ms
             << " wasapi_shared_periodicity_ms=0"
             << " wasapi_shared_event_callback=false"
             << " wasapi_shared_render_poll_ms="
             << config.wasapi_shared_render_poll_interval_ms
             << " audio_thread_mmcss_enabled="
             << (config.audio_thread_mmcss_enabled ? "true" : "false")
             << " audio_thread_mmcss_task=\""
             << config.audio_thread_mmcss_task_name
             << "\" audio_thread_mmcss_priority="
             << config.audio_thread_mmcss_priority;
      break;
    case BackendApi::kWasapiExclusive:
      expert << " wasapi_exclusive_buffer_ms="
             << config.wasapi_exclusive_buffer_duration_ms
             << " wasapi_exclusive_periodicity_ms="
             << config.wasapi_exclusive_periodicity_ms
             << " wasapi_exclusive_event_callback="
             << (config.wasapi_exclusive_event_callback_enabled ? "true"
                                                                : "false")
             << " wasapi_exclusive_alignment_retry="
             << (config.wasapi_exclusive_alignment_retry_enabled ? "true"
                                                                 : "false")
             << " wasapi_exclusive_event_timeout_ms="
             << config.wasapi_exclusive_event_timeout_ms
             << " wasapi_exclusive_render_poll_ms="
             << config.wasapi_exclusive_render_poll_interval_ms
             << " audio_thread_mmcss_enabled="
             << (config.audio_thread_mmcss_enabled ? "true" : "false")
             << " audio_thread_mmcss_task=\""
             << config.audio_thread_mmcss_task_name
             << "\" audio_thread_mmcss_priority="
             << config.audio_thread_mmcss_priority;
      break;
    case BackendApi::kAsio:
      expert << " asio_buffer_size=driver_preferred"
             << " asio_output_ready_if_supported="
             << (config.asio_use_output_ready_if_supported ? "true" : "false")
             << " asio_callbacks=driver"
             << " audio_thread_mmcss_enabled="
             << (config.audio_thread_mmcss_enabled ? "true" : "false")
             << " audio_thread_mmcss_scope=app-owned-threads-only";
      break;
    case BackendApi::kKernelStreaming:
      expert << " ks_requires_filter_pin=true"
             << " ks_state_sequence=ACQUIRE,PAUSE,RUN"
             << " ks_streaming_model=matrix-selected"
             << " ks_write_api=standard_packet_or_wavert_cyclic"
             << " ks_looped_wavert_playback=wavert_cyclic_implemented"
             << " ks_signal_mode=" << ToString(config.format.signal_mode)
             << " ks_normal_stop=valid-pcm-or-dop-silence-or-hold"
             << " audio_thread_mmcss_enabled="
             << (config.audio_thread_mmcss_enabled ? "true" : "false")
             << " audio_thread_mmcss_task=\""
             << config.audio_thread_mmcss_task_name
             << "\" audio_thread_mmcss_priority="
             << config.audio_thread_mmcss_priority;
      break;
    case BackendApi::kNull:
      expert << " null_backend_timing=simulated";
      break;
  }
  expert << " drain_before_stop=" << (settings_.drain_before_stop ? "true" : "false")
         << " drain_timeout_ms=" << settings_.drain_timeout_ms
         << " rapid_format_guard="
         << (settings_.rapid_format_cycle_guard ? "true" : "false");
  log_lines_.push_back(expert.str());

  std::ostringstream logging;
  logging << action_label << " logging settings: directory="
          << settings_.log_directory.string()
          << " format=" << ToString(settings_.log_format)
          << " level=" << ToString(settings_.log_level)
          << " initialization_dump="
          << (settings_.initialization_dump_enabled ? "true" : "false")
          << " callback_events="
          << (settings_.callback_event_logging ? "true" : "false")
          << " callback_trace_limit=" << settings_.callback_trace_limit
          << " summary_interval_ms=" << settings_.periodic_summary_interval_ms
          << " overwrite_logs=" << (settings_.overwrite_logs ? "true" : "false");
  log_lines_.push_back(logging.str());

  for (const auto& warning : settings_warnings()) {
    log_lines_.push_back(std::string("safety warning: ") + warning);
  }
}

void DiagnosticUiState::RecordLastRun(
    const PlaybackConfig& config,
    const FormatProbeResult& format_probe,
    const std::vector<DiagnosticEvent>& events) {
  last_playback_config_ = config;
  last_format_probe_ = format_probe;
  last_diagnostic_events_ = events;
  last_release_attempted_ = false;
  last_release_ok_ = false;
  last_release_backend_ = "none";
  last_release_status_ = "not-attempted";
  last_release_error_.clear();
  last_release_stats_ = {};
}

void DiagnosticUiState::RecordLastEvents(
    const std::vector<DiagnosticEvent>& events) {
  if (!last_playback_config_) {
    return;
  }
  last_diagnostic_events_ = events;
}

std::optional<DiagnosticBundleInput> DiagnosticUiState::BuildCurrentBundleInput()
    const {
  if (!last_playback_config_ || last_diagnostic_events_.empty()) {
    return std::nullopt;
  }

  DiagnosticBundleInput input;
  const auto now = std::chrono::system_clock::now();
  input.session_id = MakeUiSessionId(now);
  input.created_utc = FormatUtcTimestamp(now);
  input.config = *last_playback_config_;
  input.device = input.config.device;
  input.format_probe = last_format_probe_;
  if (input.format_probe.supported_formats.empty() &&
      input.format_probe.rejection_reasons.empty()) {
    input.format_probe.requested = input.config.format;
    if (input.config.backend == BackendApi::kKernelStreaming &&
        selected_test_condition_ &&
        selected_test_condition_->capability_status ==
            CapabilityCellStatus::kDataRangeMatch) {
      input.format_probe.rejection_reasons.push_back(
          "Kernel Streaming data_range_match is candidate evidence only");
    } else {
      input.format_probe.supported_formats.push_back(input.config.format);
    }
  }
  if (!discovery_snapshot_.devices.empty()) {
    input.discovery_snapshot = discovery_snapshot_;
  }
  input.events = last_diagnostic_events_;
  input.final_stats = stats_;
  input.release_attempted = last_release_attempted_;
  input.release_ok = last_release_ok_;
  input.release_backend = last_release_backend_;
  input.release_status = last_release_status_;
  input.release_error = last_release_error_;
  input.release_stats = last_release_stats_;
  input.pcm_summary = last_pcm_summary_.value_or(BuildPcmRunSummary(
      input.config.backend,
      input.device.stable_id,
      input.events,
      input.final_stats));
  input.build_metadata = MakeCurrentDiagnosticBuildMetadata();
  if (last_automatic_plan_) {
    input.diagnostic_plan_json = SerializeDiagnosticPlanJson(*last_automatic_plan_);
  }
  if (last_diagnostic_score_) {
    input.diagnostic_score_json =
        SerializeDiagnosticRunScoreJson(*last_diagnostic_score_);
  }
  if (selected_test_condition_) {
    input.selected_condition_json =
        BuildSelectedConditionJson(*selected_test_condition_);
  }
  input.ui_log_lines = log_lines_;
  input.summary = BuildUiBundleSummary(
      input.config,
      input.final_stats,
      status_text_,
      last_run_ok_);
  input.summary += "release_attempted=";
  input.summary += input.release_attempted ? "true\n" : "false\n";
  input.summary += "release_ok=";
  input.summary += input.release_ok ? "true\n" : "false\n";
  input.summary += "release_backend=" + input.release_backend + "\n";
  input.summary += "release_status=" + input.release_status + "\n";
  if (!input.release_error.empty()) {
    input.summary += "release_error=" + input.release_error + "\n";
  }
  input.allow_overwrite = settings_.overwrite_logs;
  return input;
}

void DiagnosticUiState::ExportDiagnosticBundle() {
  auto input = BuildCurrentBundleInput();
  if (!input) {
    last_run_ok_ = false;
    status_text_ = "nothing to export";
    log_lines_.push_back(
        "bundle export failed: run a diagnostic before exporting");
    return;
  }

  const auto base_path = BundleBasePath(settings_);
  const auto directory_result =
      WriteDiagnosticBundleDirectory(base_path, *input);
  if (!directory_result.ok) {
    last_run_ok_ = false;
    status_text_ = "bundle export error";
    log_lines_.push_back("bundle export error: " +
                         directory_result.error.message);
    return;
  }

  const auto zip_path = std::filesystem::path(base_path.string() + ".zip");
  const auto zip_result = WriteDiagnosticBundleZip(zip_path, *input);
  if (!zip_result.ok) {
    last_run_ok_ = false;
    status_text_ = "bundle zip error";
    log_lines_.push_back("bundle zip error: " + zip_result.error.message);
    bundle_path_ = base_path;
    return;
  }

  last_run_ok_ = true;
  status_text_ = "bundle exported";
  bundle_path_ = zip_path;
  log_lines_.push_back("bundle exported: " + zip_path.string());
}

std::optional<DiagnosticPlanRequest>
DiagnosticUiState::BuildAutomaticPlanRequest() const {
  if (!selected_device_ || !selected_playback_format_ ||
      !selected_playback_backend_) {
    return std::nullopt;
  }
  if (accepted_format_is_stale()) {
    return std::nullopt;
  }

  DiagnosticPlanRequest request;
  request.backend = *selected_playback_backend_;
  request.device_id = selected_device_->stable_id;
  request.known_problem_device =
      settings_.manual_known_problem_device ||
      selected_device_->is_known_problem_device;
  request.hold_mode = settings_.hold_mode;
  request.cooldown_ms =
      std::max(settings_.release_cooldown_ms, settings_.reacquire_cooldown_ms);
  request.max_reacquire_attempts = settings_.max_reacquire_attempts;
  request.expert_allow_stress = settings_.automatic_start_stop_stress_enabled;
  request.expert_allow_reinitialize = settings_.automatic_reinitialize_enabled;
  request.modes.push_back(DiagnosticTestMode::kSingleRun);
  if (settings_.automatic_format_matrix_enabled) {
    request.modes.push_back(DiagnosticTestMode::kFormatMatrix);
  }
  if (settings_.automatic_buffer_ramp_enabled) {
    request.modes.push_back(DiagnosticTestMode::kBufferRampDown);
  }
  if (settings_.automatic_start_stop_stress_enabled) {
    request.modes.push_back(DiagnosticTestMode::kStartStopStress);
  }
  if (settings_.automatic_reinitialize_enabled) {
    request.modes.push_back(DiagnosticTestMode::kReinitializeLoop);
  }
  request.formats.push_back(*selected_playback_format_);
  return request;
}

void DiagnosticUiState::PlanAutomaticSingleDeviceDiagnostic() {
  if (RejectIfActive("automatic diagnostic plan")) {
    return;
  }
  if (accepted_format_is_stale()) {
    last_run_ok_ = false;
    status_text_ = "format probe stale";
    log_lines_.push_back(
        "automatic diagnostic plan blocked: format settings changed after the last probe");
    return;
  }
  const auto request = BuildAutomaticPlanRequest();
  if (!request) {
    last_run_ok_ = false;
    status_text_ = "automatic plan needs device";
    log_lines_.push_back(
        "automatic diagnostic plan failed: select one device and accepted format first");
    return;
  }

  last_automatic_plan_ = BuildAutomaticSingleDevicePlan(*request);
  last_diagnostic_score_.reset();
  last_run_ok_ = last_automatic_plan_->accepted;
  status_text_ = last_automatic_plan_->accepted
      ? "automatic plan ready"
      : "automatic plan rejected";
  std::ostringstream line;
  line << "automatic diagnostic plan: accepted="
       << (last_automatic_plan_->accepted ? "true" : "false")
       << " steps=" << last_automatic_plan_->steps.size()
       << " opens_audio_device="
       << (last_automatic_plan_->opens_audio_device ? "true" : "false")
       << " cooldown_ms=" << last_automatic_plan_->cooldown_ms
       << " max_reacquire_attempts="
       << last_automatic_plan_->max_reacquire_attempts;
  log_lines_.push_back(line.str());
  for (const auto& reason : last_automatic_plan_->rejection_reasons) {
    log_lines_.push_back("automatic diagnostic rejection: " + reason);
  }
}

void DiagnosticUiState::RunAutomaticSingleDeviceDiagnostic() {
  if (RejectIfActive("automatic diagnostic run")) {
    return;
  }
  PlanAutomaticSingleDeviceDiagnostic();
  if (!last_automatic_plan_ || !last_automatic_plan_->accepted) {
    return;
  }
  if (last_automatic_plan_->steps.empty()) {
    last_run_ok_ = false;
    status_text_ = "automatic plan empty";
    log_lines_.push_back("automatic diagnostic run failed: plan has no steps");
    return;
  }
  for (const auto& step : last_automatic_plan_->steps) {
    if (step.mode != DiagnosticTestMode::kSingleRun) {
      last_run_ok_ = false;
      status_text_ = "automatic plan only";
      log_lines_.push_back(
          "automatic diagnostic run blocked: only the single-run step is executable in this slice");
      return;
    }
  }

  const auto backend = *selected_playback_backend_;
  const auto signal = selected_playback_format_->signal_mode;
  if (backend == BackendApi::kMme) {
    StartMmePcm();
  } else if (backend == BackendApi::kDirectSound) {
    StartDirectSoundPcm();
  } else if (backend == BackendApi::kWasapiShared) {
    StartWasapiSharedPcm();
  } else if (backend == BackendApi::kWasapiExclusive &&
             signal == SignalMode::kDop) {
    StartWasapiExclusiveDop();
  } else if (backend == BackendApi::kWasapiExclusive) {
    StartWasapiExclusivePcm();
  } else if (backend == BackendApi::kKernelStreaming) {
    StartKernelStreamingPcm();
  } else if (backend == BackendApi::kAsio &&
             signal == SignalMode::kAsioNativeDsd) {
    StartAsioNativeDsd();
  } else if (backend == BackendApi::kAsio && signal == SignalMode::kDop) {
    StartAsioDop();
  } else if (backend == BackendApi::kAsio) {
    StartAsioPcm();
  } else {
    RunNullSession();
  }

  const bool run_ok = last_run_ok_;
  last_diagnostic_score_ =
      ScoreDiagnosticRun(*last_automatic_plan_, stats_, run_ok);
  std::ostringstream score_line;
  score_line << "automatic diagnostic score="
             << last_diagnostic_score_->score
             << " rating=" << last_diagnostic_score_->rating;
  log_lines_.push_back(score_line.str());
  for (const auto& penalty : last_diagnostic_score_->penalties) {
    log_lines_.push_back("automatic diagnostic penalty: " + penalty);
  }

  if (has_exportable_diagnostic()) {
    ExportDiagnosticBundle();
  }
}

void DiagnosticUiState::RunNullSession(std::optional<std::filesystem::path> bundle_path) {
  if (RejectIfActive("Null diagnostic start")) {
    return;
  }
  PlaybackConfig config;
  config.backend = BackendApi::kNull;
  config.duration_ms = 100;
  config.hold_mode = HoldMode::kKeepWarmAfterStop;

  const auto session = RunNullDiagnosticSession(config, bundle_path);
  stats_ = session.stats;
  log_lines_.clear();
  for (const auto& event : session.events) {
    std::ostringstream line;
    line << '#' << event.sequence << ' ' << ToString(event.type) << ": "
         << event.message;
    log_lines_.push_back(line.str());
  }

  last_run_ok_ = session.result.ok;
  status_text_ = session.result.ok ? "ready" : "error";
  last_backend_error_summary_ = session.result.ok
      ? "none"
      : session.result.error.message;
  bundle_path_ = session.bundle_directory;
  RecordLastRun(session.config, session.format_probe, session.events);
  last_pcm_summary_ = BuildPcmRunSummary(
      BackendApi::kNull,
      "null-device",
      session.events,
      session.stats);
  if (!session.result.ok) {
    log_lines_.push_back("error: " + session.result.error.message);
  }
}

void DiagnosticUiState::LoadDiscoverySnapshot(DiscoverySnapshot snapshot) {
  if (RejectIfActive("discovery snapshot load")) {
    return;
  }
  discovery_snapshot_ = std::move(snapshot);
  selected_device_.reset();
  ResetAcceptedFormatSelection();
  bundle_path_.reset();
  last_pcm_summary_.reset();
  last_playback_config_.reset();
  ClearProbeRows();
  last_diagnostic_events_.clear();
  last_automatic_plan_.reset();
  last_diagnostic_score_.reset();
  ClearDeviceCapabilityMatrix();
  last_backend_error_summary_ = "none";
  log_lines_.clear();

  std::ostringstream summary;
  summary << "discovery snapshot: backend=" << ToString(discovery_snapshot_.backend)
          << " devices=" << discovery_snapshot_.devices.size()
          << " safe_dry_run="
          << (DiscoverySnapshotIsSafeDryRun(discovery_snapshot_) ? "true" : "false");
  log_lines_.push_back(summary.str());

  for (const auto& device : discovery_snapshot_.devices) {
    std::ostringstream line;
    line << "device " << device.device.display_name
         << " id=" << device.device.stable_id
         << " availability=" << ToString(device.availability);
    if (device.device.is_default) {
      line << " default=true";
    }
    if (device.device.is_known_problem_device) {
      line << " known_problem=true";
    }
    log_lines_.push_back(line.str());
  }

  last_run_ok_ = DiscoverySnapshotIsSafeDryRun(discovery_snapshot_);
  status_text_ = last_run_ok_ ? "devices loaded" : "unsafe discovery snapshot";
}

void DiagnosticUiState::LoadProbeSnapshotForCurrentFormat(
    DiscoverySnapshot snapshot) {
  LoadDiscoverySnapshot(std::move(snapshot));
  if (!HasAnyActiveBackend()) {
    MarkProbeRowsFreshForCurrentFormat();
  }
}

void DiagnosticUiState::RefreshWasapiEndpoints() {
  if (RejectIfActive("WASAPI refresh")) {
    return;
  }
  if (!IsWasapiEndpointMode(settings_.requested_backend)) {
    last_run_ok_ = false;
    status_text_ = "backend mismatch";
    log_lines_.push_back(
        "WASAPI refresh blocked: select WASAPI shared or WASAPI exclusive as the device-list API first");
    return;
  }
  auto snapshot = EnumerateWasapiRenderEndpoints();
  RetagWasapiSnapshotForRequestedMode(snapshot, settings_.requested_backend);
  snapshot.capture_utc = settings_.requested_backend == BackendApi::kWasapiExclusive
      ? "manual-wasapi-exclusive-refresh"
      : "manual-wasapi-shared-refresh";
  LoadDiscoverySnapshot(std::move(snapshot));
}

void DiagnosticUiState::RefreshMmeDevices() {
  if (RejectIfActive("MME refresh")) {
    return;
  }
  if (RejectIfRequestedBackendIsNot(BackendApi::kMme, "MME refresh")) {
    return;
  }
  auto snapshot = EnumerateMmeWaveOutDevices();
  snapshot.capture_utc = "manual-mme-refresh";
  LoadDiscoverySnapshot(std::move(snapshot));
}

void DiagnosticUiState::RefreshDirectSoundDevices() {
  if (RejectIfActive("DirectSound refresh")) {
    return;
  }
  if (RejectIfRequestedBackendIsNot(BackendApi::kDirectSound,
                                    "DirectSound refresh")) {
    return;
  }
  auto snapshot = EnumerateDirectSoundOutputDevices();
  snapshot.capture_utc = "manual-directsound-refresh";
  LoadDiscoverySnapshot(std::move(snapshot));
}

void DiagnosticUiState::RefreshAsioDrivers() {
  if (RejectIfActive("ASIO refresh")) {
    return;
  }
  if (RejectIfRequestedBackendIsNot(BackendApi::kAsio, "ASIO refresh")) {
    return;
  }
  auto snapshot = EnumerateAsioDrivers();
  snapshot.capture_utc = "manual-asio-refresh";
  LoadDiscoverySnapshot(std::move(snapshot));
  log_lines_.push_back(
      "ASIO discovery note: driver instantiation, buffers, playback, and "
      "control panel opening are not performed by discovery");
}

void DiagnosticUiState::RefreshKernelStreamingDevices() {
  if (RejectIfActive("Kernel Streaming refresh")) {
    return;
  }
  if (RejectIfRequestedBackendIsNot(BackendApi::kKernelStreaming,
                                    "Kernel Streaming refresh")) {
    return;
  }

  auto snapshot = EnumerateKernelStreamingDevices();
  snapshot.capture_utc = "manual-kernel-streaming-refresh";
  LoadDiscoverySnapshot(std::move(snapshot));
  log_lines_.push_back(
      "Kernel Streaming refresh note: bounded filter/pin/data-range discovery may open filters, but no pin stream is set to RUN and no audio buffers are submitted");
}

void DiagnosticUiState::ProbeSelectedAsioPcmFormats() {
  if (RejectIfActive("ASIO PCM probe")) {
    return;
  }
  if (!selected_device_) {
    last_run_ok_ = false;
    status_text_ = "device not selected";
    log_lines_.push_back("ASIO PCM probe failed: no explicit ASIO driver selected");
    return;
  }
  if (selected_device_->backend != BackendApi::kAsio) {
    last_run_ok_ = false;
    status_text_ = "ASIO driver not selected";
    log_lines_.push_back(
        "ASIO PCM probe failed: selected device is not an ASIO driver");
    return;
  }
  if (RejectIfRequestedBackendIsNot(BackendApi::kAsio,
                                    "ASIO PCM probe") ||
      RejectIfRequestedSignalIsNot(SignalMode::kPcm,
                                   "ASIO PCM probe")) {
    return;
  }

  AsioPcmBackend backend;
  const auto probe_result = backend.probeFormats(*selected_device_);

  DiscoverySnapshot snapshot;
  snapshot.backend = BackendApi::kAsio;
  snapshot.capture_utc = "manual-asio-pcm-format-probe";
  snapshot.opens_audio_device = IsAsioSdkEnabled();
  snapshot.initializes_stream = IsAsioSdkEnabled();
  snapshot.starts_stream = false;

  auto device_snapshot = MakeDiscoveredDeviceSnapshot(
      *selected_device_,
      DeviceAvailability::kActive);
  for (const auto& format : probe_result.supported_formats) {
    CapabilityProbeRecord record;
    record.kind = CapabilityProbeKind::kFormatSupport;
    record.support = CapabilitySupport::kSupported;
    record.requested_format = probe_result.requested;
    record.accepted_format = format;
    record.detail = "ASIO PCM output format accepted for selected driver";
    record.backend_fields["api"] = "ASIO driver query";
    record.backend_fields["creates_buffers"] = "false";
    record.backend_fields["starts_stream"] = "false";
    record.backend_fields["opens_control_panel"] = "false";
    device_snapshot.probes.push_back(std::move(record));
  }
  if (device_snapshot.probes.empty()) {
    CapabilityProbeRecord record;
    record.kind = CapabilityProbeKind::kFormatSupport;
    record.support = CapabilitySupport::kFailed;
    record.requested_format = probe_result.requested;
    record.detail = probe_result.rejection_reasons.empty()
        ? "ASIO PCM probe did not return a supported format"
        : probe_result.rejection_reasons.front();
    record.backend_fields["creates_buffers"] = "false";
    record.backend_fields["starts_stream"] = "false";
    record.backend_fields["opens_control_panel"] = "false";
    device_snapshot.probes.push_back(std::move(record));
  }

  const std::string stable_id = selected_device_->stable_id;
  snapshot.devices.push_back(std::move(device_snapshot));
  LoadProbeSnapshotForCurrentFormat(std::move(snapshot));
  SelectDiscoveredDeviceById(stable_id);
  const bool has_format = selected_playback_format_.has_value() &&
                          selected_playback_backend_ == BackendApi::kAsio;
  last_run_ok_ = has_format;
  status_text_ = has_format ? "ASIO PCM probed" : "ASIO PCM probe unavailable";
  log_lines_.push_back(
      "ASIO PCM probe note: driver start is not performed by this probe");
}

void DiagnosticUiState::ProbeSelectedAsioDopFormats() {
  if (RejectIfActive("ASIO DoP probe")) {
    return;
  }
  if (!selected_device_) {
    last_run_ok_ = false;
    status_text_ = "device not selected";
    log_lines_.push_back(
        "ASIO DoP probe failed: no explicit ASIO driver selected");
    return;
  }
  if (selected_device_->backend != BackendApi::kAsio) {
    last_run_ok_ = false;
    status_text_ = "ASIO driver not selected";
    log_lines_.push_back(
        "ASIO DoP probe failed: selected device is not an ASIO driver");
    return;
  }
  if (RejectIfRequestedBackendIsNot(BackendApi::kAsio,
                                    "ASIO DoP probe") ||
      RejectIfRequestedSignalIsNot(SignalMode::kDop,
                                   "ASIO DoP probe")) {
    return;
  }

  AsioPcmBackend backend;
  DopConfig requested_dop;
  requested_dop.dsd_rate_multiplier = settings_.requested_dsd_rate_multiplier;
  requested_dop.channel_count = settings_.requested_channel_count;
  if (settings_.requested_sample_type == SampleType::kDsd1BitMsbFirst) {
    requested_dop.dsd_byte_order = SampleType::kDsd1BitMsbFirst;
  }
  const auto probe_result =
      backend.probeDopFormats(*selected_device_, requested_dop);

  DiscoverySnapshot snapshot;
  snapshot.backend = BackendApi::kAsio;
  snapshot.capture_utc = "manual-asio-dop-format-probe";
  snapshot.opens_audio_device = IsAsioSdkEnabled();
  snapshot.initializes_stream = IsAsioSdkEnabled();
  snapshot.starts_stream = false;

  auto device_snapshot = MakeDiscoveredDeviceSnapshot(
      *selected_device_,
      DeviceAvailability::kActive);
  for (const auto& format : probe_result.supported_formats) {
    CapabilityProbeRecord record;
    record.kind = CapabilityProbeKind::kFormatSupport;
    record.support = CapabilitySupport::kSupported;
    record.requested_format = probe_result.requested;
    record.accepted_format = format;
    record.detail = "ASIO DoP PCM carrier format accepted for selected driver";
    record.backend_fields["api"] = "ASIO DoP carrier query";
    record.backend_fields["creates_buffers"] = "false";
    record.backend_fields["starts_stream"] = "false";
    record.backend_fields["opens_control_panel"] = "false";
    record.backend_fields["keep_alive_format"] = "valid-dop-silence";
    record.backend_fields["exact_carrier_required"] = "true";
    record.backend_fields["pcm_carrier_sample_type"] =
        ToString(format.sample_type);
    if (format.dsd_rate_multiplier) {
      record.backend_fields["dop_dsd_rate_multiplier"] =
          std::to_string(*format.dsd_rate_multiplier);
    }
    device_snapshot.probes.push_back(std::move(record));
  }
  if (device_snapshot.probes.empty()) {
    CapabilityProbeRecord record;
    record.kind = CapabilityProbeKind::kFormatSupport;
    record.support = CapabilitySupport::kFailed;
    record.requested_format = probe_result.requested;
    record.detail = probe_result.rejection_reasons.empty()
        ? "ASIO DoP carrier probe did not return a supported format"
        : probe_result.rejection_reasons.front();
    record.backend_fields["api"] = "ASIO DoP carrier query";
    record.backend_fields["creates_buffers"] = "false";
    record.backend_fields["starts_stream"] = "false";
    record.backend_fields["opens_control_panel"] = "false";
    record.backend_fields["keep_alive_format"] = "valid-dop-silence";
    record.backend_fields["exact_carrier_required"] = "true";
    device_snapshot.probes.push_back(std::move(record));
  }

  const std::string stable_id = selected_device_->stable_id;
  snapshot.devices.push_back(std::move(device_snapshot));
  LoadProbeSnapshotForCurrentFormat(std::move(snapshot));
  SelectDiscoveredDeviceById(stable_id);
  const bool has_format = selected_playback_format_.has_value() &&
                          selected_playback_backend_ == BackendApi::kAsio &&
                          IsAsioDopCarrierFormat(*selected_playback_format_);
  last_run_ok_ = has_format;
  status_text_ = has_format ? "ASIO DoP probed" : "ASIO DoP probe unavailable";
  log_lines_.push_back(
      "ASIO DoP probe note: GUI-requested DSD rate and channel count are included; exact PCM carrier support is required; driver start "
      "and control panel opening are not performed by this probe");
}

void DiagnosticUiState::ProbeSelectedAsioNativeDsdFormats() {
  if (RejectIfActive("ASIO native DSD probe")) {
    return;
  }
  if (!selected_device_) {
    last_run_ok_ = false;
    status_text_ = "device not selected";
    log_lines_.push_back(
        "ASIO native DSD probe failed: no explicit ASIO driver selected");
    return;
  }
  if (selected_device_->backend != BackendApi::kAsio) {
    last_run_ok_ = false;
    status_text_ = "ASIO driver not selected";
    log_lines_.push_back(
        "ASIO native DSD probe failed: selected device is not an ASIO driver");
    return;
  }
  if (RejectIfRequestedBackendIsNot(BackendApi::kAsio,
                                    "ASIO native DSD probe") ||
      RejectIfRequestedSignalIsNot(SignalMode::kAsioNativeDsd,
                                   "ASIO native DSD probe")) {
    return;
  }

  AsioNativeDsdBackend backend;
  NativeDsdConfig requested_dsd;
  requested_dsd.dsd_rate_multiplier = settings_.requested_dsd_rate_multiplier;
  requested_dsd.channel_count = settings_.requested_channel_count;
  if (IsSupportedNativeDsdSampleType(settings_.requested_sample_type)) {
    requested_dsd.sample_type = settings_.requested_sample_type;
  }
  const auto probe_result =
      backend.probeFormats(*selected_device_, requested_dsd);

  DiscoverySnapshot snapshot;
  snapshot.backend = BackendApi::kAsio;
  snapshot.capture_utc = "manual-asio-native-dsd-format-probe";
  snapshot.opens_audio_device = IsAsioSdkEnabled();
  snapshot.initializes_stream = IsAsioSdkEnabled();
  snapshot.starts_stream = false;

  auto device_snapshot = MakeDiscoveredDeviceSnapshot(
      *selected_device_,
      DeviceAvailability::kActive);
  for (const auto& format : probe_result.supported_formats) {
    CapabilityProbeRecord record;
    record.kind = CapabilityProbeKind::kFormatSupport;
    record.support = CapabilitySupport::kSupported;
    record.requested_format = probe_result.requested;
    record.accepted_format = format;
    record.detail = "ASIO native DSD format accepted for selected driver";
    record.backend_fields["api"] = "ASIO native DSD query";
    record.backend_fields["starts_stream"] = "false";
    record.backend_fields["opens_control_panel"] = "false";
    record.backend_fields["keep_alive_format"] = "valid-dsd-idle";
    device_snapshot.probes.push_back(std::move(record));
  }
  if (device_snapshot.probes.empty()) {
    CapabilityProbeRecord record;
    record.kind = CapabilityProbeKind::kFormatSupport;
    record.support = CapabilitySupport::kFailed;
    record.requested_format = probe_result.requested;
    record.detail = probe_result.rejection_reasons.empty()
        ? "ASIO native DSD probe did not return a supported format"
        : probe_result.rejection_reasons.front();
    record.backend_fields["starts_stream"] = "false";
    record.backend_fields["opens_control_panel"] = "false";
    record.backend_fields["keep_alive_format"] = "valid-dsd-idle";
    device_snapshot.probes.push_back(std::move(record));
  }

  const std::string stable_id = selected_device_->stable_id;
  snapshot.devices.push_back(std::move(device_snapshot));
  LoadProbeSnapshotForCurrentFormat(std::move(snapshot));
  SelectDiscoveredDeviceById(stable_id);
  const bool has_format = selected_playback_format_.has_value() &&
                          selected_playback_backend_ == BackendApi::kAsio &&
                          selected_playback_format_->signal_mode ==
                              SignalMode::kAsioNativeDsd;
  last_run_ok_ = has_format;
  status_text_ = has_format
      ? "ASIO native DSD probed"
      : "ASIO native DSD probe unavailable";
  log_lines_.push_back(
      "ASIO native DSD probe note: GUI-requested DSD rate, channel count, and sample type are included; driver start is not performed by this probe");
}

void DiagnosticUiState::ProbeSelectedMmeFormats() {
  if (RejectIfActive("MME format probe")) {
    return;
  }
  if (!selected_device_) {
    last_run_ok_ = false;
    status_text_ = "device not selected";
    log_lines_.push_back(
        "MME format probe failed: no explicit waveOut device selected");
    return;
  }
  if (selected_device_->backend != BackendApi::kMme) {
    last_run_ok_ = false;
    status_text_ = "MME device not selected";
    log_lines_.push_back(
        "MME format probe failed: selected device is not MME");
    return;
  }
  if (RejectIfRequestedBackendIsNot(BackendApi::kMme,
                                    "MME format probe") ||
      RejectIfRequestedSignalIsNot(SignalMode::kPcm,
                                   "MME format probe")) {
    return;
  }

  const auto device_id = MmeDeviceIdFromStableId(selected_device_->stable_id);
  if (!device_id) {
    last_run_ok_ = false;
    status_text_ = "MME device ID invalid";
    log_lines_.push_back(
        "MME format probe failed: selected stable ID could not be parsed");
    return;
  }

  MmeFormatProbeRequest request;
  request.device_id = *device_id;
  PushUniqueFormat(request.candidate_formats,
                   BuildRequestedPcmFormatFromSettings());
  for (const auto& candidate : MmeDefaultPcmCandidates()) {
    PushUniqueFormat(request.candidate_formats, candidate);
  }

  DiscoverySnapshot snapshot;
  snapshot.backend = BackendApi::kMme;
  snapshot.capture_utc = "manual-mme-format-probe";
  snapshot.opens_audio_device = false;
  snapshot.initializes_stream = false;
  snapshot.starts_stream = false;

  auto probe = ProbeMmeWaveOutFormats(request);
  const bool probe_has_error = probe.discovery_error.has_value();
  snapshot.devices.push_back(std::move(probe));

  const std::string stable_id = selected_device_->stable_id;
  LoadProbeSnapshotForCurrentFormat(std::move(snapshot));
  SelectDiscoveredDeviceById(stable_id);
  last_run_ok_ = !probe_has_error;
  status_text_ = probe_has_error ? "MME probe error" : "MME probed";
  log_lines_.push_back(
      "MME probe note: GUI-requested PCM format is included before conservative candidates");
}

void DiagnosticUiState::ProbeSelectedDirectSoundFormats() {
  if (RejectIfActive("DirectSound format probe")) {
    return;
  }
  if (!selected_device_) {
    last_run_ok_ = false;
    status_text_ = "device not selected";
    log_lines_.push_back(
        "DirectSound format probe failed: no explicit device selected");
    return;
  }
  if (selected_device_->backend != BackendApi::kDirectSound) {
    last_run_ok_ = false;
    status_text_ = "DirectSound device not selected";
    log_lines_.push_back(
        "DirectSound format probe failed: selected device is not DirectSound");
    return;
  }
  if (RejectIfRequestedBackendIsNot(BackendApi::kDirectSound,
                                    "DirectSound format probe") ||
      RejectIfRequestedSignalIsNot(SignalMode::kPcm,
                                   "DirectSound format probe")) {
    return;
  }

  DirectSoundFormatProbeRequest request;
  request.stable_id = selected_device_->stable_id;
  PushUniqueFormat(request.candidate_formats,
                   BuildRequestedPcmFormatFromSettings());
  for (const auto& candidate : DirectSoundDefaultPcmCandidates()) {
    PushUniqueFormat(request.candidate_formats, candidate);
  }

  DiscoverySnapshot snapshot;
  snapshot.backend = BackendApi::kDirectSound;
  snapshot.capture_utc = "manual-directsound-format-probe";
  snapshot.opens_audio_device = true;
  snapshot.initializes_stream = false;
  snapshot.starts_stream = false;

  auto probe = ProbeDirectSoundDeviceFormats(request);
  const bool probe_has_error = probe.discovery_error.has_value();
  snapshot.devices.push_back(std::move(probe));

  LoadProbeSnapshotForCurrentFormat(std::move(snapshot));
  SelectDiscoveredDeviceById(request.stable_id);
  last_run_ok_ = !probe_has_error;
  status_text_ = probe_has_error
      ? "DirectSound probe error"
      : "DirectSound probed";
  log_lines_.push_back(
      "DirectSound probe note: secondary buffers are created and released "
      "without Play, Lock, Unlock, or Restore");
  log_lines_.push_back(
      "DirectSound probe note: GUI-requested PCM format is included before conservative candidates");
}

void DiagnosticUiState::ProbeSelectedWasapiFormats(bool exclusive_mode) {
  if (RejectIfActive(exclusive_mode ? "WASAPI exclusive format probe"
                                    : "WASAPI shared format probe")) {
    return;
  }
  if (!selected_device_) {
    last_run_ok_ = false;
    status_text_ = "device not selected";
    log_lines_.push_back("format probe failed: no explicit endpoint selected");
    return;
  }
  const BackendApi requested_backend = exclusive_mode
      ? BackendApi::kWasapiExclusive
      : BackendApi::kWasapiShared;
  if (RejectIfSelectedDeviceIsNotWasapiEndpoint(
          exclusive_mode ? "WASAPI exclusive format probe"
                         : "WASAPI shared format probe") ||
      RejectIfRequestedBackendIsNot(
          requested_backend,
          exclusive_mode ? "WASAPI exclusive format probe"
                         : "WASAPI shared format probe") ||
      RejectIfRequestedSignalIsNot(
          SignalMode::kPcm,
          exclusive_mode ? "WASAPI exclusive format probe"
                         : "WASAPI shared format probe")) {
    return;
  }
  if (selected_device_->backend != requested_backend) {
    last_run_ok_ = false;
    status_text_ = "backend mismatch";
    log_lines_.push_back(
        "WASAPI format probe failed: selected endpoint was not loaded for the current target API");
    return;
  }

  WasapiFormatProbeRequest request;
  request.endpoint_id = selected_device_->stable_id;
  request.exclusive_mode = exclusive_mode;
  PushUniqueFormat(request.candidate_formats,
                   BuildRequestedPcmFormatFromSettings());
  for (const auto& candidate : WasapiDefaultPcmCandidates()) {
    PushUniqueFormat(request.candidate_formats, candidate);
  }

  DiscoverySnapshot snapshot;
  snapshot.backend = exclusive_mode
      ? BackendApi::kWasapiExclusive
      : BackendApi::kWasapiShared;
  snapshot.capture_utc = "manual-format-probe";
  snapshot.opens_audio_device = false;
  snapshot.initializes_stream = false;
  snapshot.starts_stream = false;
  snapshot.devices.push_back(ProbeWasapiEndpointFormats(request));
  LoadProbeSnapshotForCurrentFormat(std::move(snapshot));
  SelectDiscoveredDeviceById(request.endpoint_id);
  log_lines_.push_back(
      "WASAPI probe note: GUI-requested PCM format is included before fallback candidates");
}

void DiagnosticUiState::ProbeSelectedWasapiDopFormats() {
  if (RejectIfActive("WASAPI DoP format probe")) {
    return;
  }
  if (!selected_device_) {
    last_run_ok_ = false;
    status_text_ = "device not selected";
    log_lines_.push_back("DoP format probe failed: no explicit endpoint selected");
    return;
  }
  if (RejectIfSelectedDeviceIsNotWasapiEndpoint("WASAPI DoP format probe") ||
      RejectIfRequestedBackendIsNot(BackendApi::kWasapiExclusive,
                                    "WASAPI DoP format probe") ||
      RejectIfRequestedSignalIsNot(SignalMode::kDop,
                                   "WASAPI DoP format probe")) {
    return;
  }
  if (selected_device_->backend != BackendApi::kWasapiExclusive) {
    last_run_ok_ = false;
    status_text_ = "backend mismatch";
    log_lines_.push_back(
        "WASAPI DoP format probe failed: endpoint was not loaded for WASAPI exclusive");
    return;
  }

  WasapiFormatProbeRequest request;
  request.endpoint_id = selected_device_->stable_id;
  request.exclusive_mode = true;
  request.include_mix_format_candidate = false;
  PushUniqueFormat(request.candidate_formats,
                   BuildRequestedDopCarrierFromSettings());
  for (const auto& candidate :
       WasapiDefaultDopCarrierCandidates(settings_.requested_channel_count)) {
    PushUniqueFormat(request.candidate_formats, candidate);
  }

  DiscoverySnapshot snapshot;
  snapshot.backend = BackendApi::kWasapiExclusive;
  snapshot.capture_utc = "manual-dop-format-probe";
  snapshot.opens_audio_device = false;
  snapshot.initializes_stream = false;
  snapshot.starts_stream = false;
  snapshot.devices.push_back(ProbeWasapiEndpointFormats(request));
  LoadProbeSnapshotForCurrentFormat(std::move(snapshot));
  SelectDiscoveredDeviceById(request.endpoint_id);
  log_lines_.push_back(
      "DoP probe note: GUI-requested DSD rate and channel count are included; exact WASAPI exclusive carrier support is required");
}

void DiagnosticUiState::StartWasapiSharedPcm() {
  if (HasAnyActiveBackend()) {
    EnsureStartSafety("WASAPI shared start");
    return;
  }
  if (!selected_device_) {
    last_run_ok_ = false;
    status_text_ = "device not selected";
    log_lines_.push_back("WASAPI shared start failed: no explicit endpoint selected");
    return;
  }
  if (!selected_playback_format_) {
    last_run_ok_ = false;
    status_text_ = "format not accepted";
    log_lines_.push_back(
        "WASAPI shared start failed: run selected-endpoint format probe first");
    return;
  }
  if (!selected_playback_backend_ ||
      *selected_playback_backend_ != BackendApi::kWasapiShared) {
    last_run_ok_ = false;
    status_text_ = "shared format not accepted";
    log_lines_.push_back(
        "WASAPI shared start failed: selected format was not accepted for shared mode");
    return;
  }
  if (!EnsureStartSafety("WASAPI shared start")) {
    return;
  }

  PlaybackConfig config;
  config.backend = BackendApi::kWasapiShared;
  config.device = *selected_device_;
  config.format = *selected_playback_format_;
  ApplySettingsToConfig(config);
  AppendRequestedSettingsLog(config, "WASAPI shared start");

  wasapi_shared_backend_ = std::make_unique<WasapiSharedPcmBackend>();
  wasapi_shared_event_count_ = 0;

  auto result = wasapi_shared_backend_->initialize(config);
  AppendWasapiSharedEvents();
  if (result.ok) {
    result = wasapi_shared_backend_->start();
    AppendWasapiSharedEvents();
  }

  stats_ = wasapi_shared_backend_->getRealtimeStats();
  const auto events = wasapi_shared_backend_->diagnostic_events();
  RecordLastRun(config,
                FormatProbeForRun(config, selected_test_condition_, result.ok),
                events);
  last_pcm_summary_ = BuildPcmRunSummary(
      BackendApi::kWasapiShared,
      config.device.stable_id,
      events,
      stats_);
  last_run_ok_ = result.ok;
  status_text_ = result.ok ? "WASAPI shared running" : "WASAPI shared error";
  if (!result.ok) {
    log_lines_.push_back("WASAPI shared error: " + result.error.message);
  }
}

void DiagnosticUiState::StartMmePcm() {
  if (HasAnyActiveBackend()) {
    EnsureStartSafety("MME start");
    return;
  }
  if (!selected_device_) {
    last_run_ok_ = false;
    status_text_ = "device not selected";
    log_lines_.push_back("MME start failed: no explicit waveOut device selected");
    return;
  }
  if (!selected_playback_format_) {
    last_run_ok_ = false;
    status_text_ = "format not accepted";
    log_lines_.push_back("MME start failed: refresh/probe MME formats first");
    return;
  }
  if (!selected_playback_backend_ ||
      *selected_playback_backend_ != BackendApi::kMme) {
    last_run_ok_ = false;
    status_text_ = "MME format not accepted";
    log_lines_.push_back("MME start failed: selected format was not accepted for MME");
    return;
  }
  if (!EnsureStartSafety("MME start")) {
    return;
  }

  PlaybackConfig config;
  config.backend = BackendApi::kMme;
  config.device = *selected_device_;
  config.device.backend = BackendApi::kMme;
  config.format = *selected_playback_format_;
  ApplySettingsToConfig(config);
  AppendRequestedSettingsLog(config, "MME start");

  mme_backend_ = std::make_unique<MmePcmBackend>();
  mme_event_count_ = 0;

  auto result = mme_backend_->initialize(config);
  AppendMmeEvents();
  if (result.ok) {
    result = mme_backend_->start();
    AppendMmeEvents();
  }

  stats_ = mme_backend_->getRealtimeStats();
  const auto events = mme_backend_->diagnostic_events();
  RecordLastRun(config,
                FormatProbeForRun(config, selected_test_condition_, result.ok),
                events);
  last_pcm_summary_ = BuildPcmRunSummary(
      BackendApi::kMme,
      config.device.stable_id,
      events,
      stats_);
  last_run_ok_ = result.ok;
  status_text_ = result.ok ? "MME running" : "MME error";
  if (!result.ok) {
    log_lines_.push_back("MME error: " + result.error.message);
  }
}

void DiagnosticUiState::StartDirectSoundPcm() {
  if (HasAnyActiveBackend()) {
    EnsureStartSafety("DirectSound start");
    return;
  }
  if (!selected_device_) {
    last_run_ok_ = false;
    status_text_ = "device not selected";
    log_lines_.push_back(
        "DirectSound start failed: no explicit DirectSound device selected");
    return;
  }
  if (!selected_playback_format_) {
    last_run_ok_ = false;
    status_text_ = "format not accepted";
    log_lines_.push_back(
        "DirectSound start failed: run selected-device DirectSound probe first");
    return;
  }
  if (!selected_playback_backend_ ||
      *selected_playback_backend_ != BackendApi::kDirectSound) {
    last_run_ok_ = false;
    status_text_ = "DirectSound format not accepted";
    log_lines_.push_back(
        "DirectSound start failed: selected format was not accepted for DirectSound");
    return;
  }
  if (!EnsureStartSafety("DirectSound start")) {
    return;
  }

  PlaybackConfig config;
  config.backend = BackendApi::kDirectSound;
  config.device = *selected_device_;
  config.device.backend = BackendApi::kDirectSound;
  config.format = *selected_playback_format_;
  ApplySettingsToConfig(config);
  AppendRequestedSettingsLog(config, "DirectSound start");

  directsound_backend_ = std::make_unique<DirectSoundPcmBackend>();
  directsound_event_count_ = 0;

  auto result = directsound_backend_->initialize(config);
  AppendDirectSoundEvents();
  if (result.ok) {
    result = directsound_backend_->start();
    AppendDirectSoundEvents();
  }

  stats_ = directsound_backend_->getRealtimeStats();
  const auto events = directsound_backend_->diagnostic_events();
  RecordLastRun(config,
                FormatProbeForRun(config, selected_test_condition_, result.ok),
                events);
  last_pcm_summary_ = BuildPcmRunSummary(
      BackendApi::kDirectSound,
      config.device.stable_id,
      events,
      stats_);
  last_run_ok_ = result.ok;
  status_text_ = result.ok ? "DirectSound running" : "DirectSound error";
  if (!result.ok) {
    log_lines_.push_back("DirectSound error: " + result.error.message);
  }
}

void DiagnosticUiState::StartKernelStreamingPcm() {
  if (HasAnyActiveBackend()) {
    EnsureStartSafety("Kernel Streaming start");
    return;
  }
  if (!selected_device_) {
    last_run_ok_ = false;
    status_text_ = "device not selected";
    log_lines_.push_back(
        "Kernel Streaming start failed: no explicit filter/pin selected");
    return;
  }
  if (!selected_playback_format_) {
    last_run_ok_ = false;
    status_text_ = "format not accepted";
    log_lines_.push_back(
        "Kernel Streaming start failed: build the capability matrix and select an accepted PCM/DoP carrier format first");
    return;
  }
  if (!selected_playback_backend_ ||
      *selected_playback_backend_ != BackendApi::kKernelStreaming) {
    last_run_ok_ = false;
    status_text_ = "Kernel Streaming format not accepted";
    log_lines_.push_back(
        "Kernel Streaming start failed: selected format was not accepted for Kernel Streaming");
    return;
  }
  if (!IsKernelStreamingPlaybackFormat(*selected_playback_format_)) {
    last_run_ok_ = false;
    status_text_ = "Kernel Streaming format unsupported";
    log_lines_.push_back(
        "Kernel Streaming start failed: selected format is not a supported PCM format or exact DoP carrier");
    return;
  }
  if (!EnsureStartSafety("Kernel Streaming start")) {
    return;
  }

  PlaybackConfig config;
  config.backend = BackendApi::kKernelStreaming;
  config.device = *selected_device_;
  config.device.backend = BackendApi::kKernelStreaming;
  config.format = *selected_playback_format_;
  ApplySettingsToConfig(config);
  AppendRequestedSettingsLog(config, "Kernel Streaming start");
  const bool ks_data_range_candidate =
      selected_test_condition_ &&
      selected_test_condition_->capability_status ==
          CapabilityCellStatus::kDataRangeMatch;
  if (ks_data_range_candidate) {
    log_lines_.push_back(
        "Kernel Streaming start verification: selected matrix cell is a KSDATARANGE data_range_match candidate; pin creation and RUN start are not pre-verified");
  }

  kernel_streaming_backend_ = std::make_unique<KernelStreamingPcmBackend>();
  kernel_streaming_event_count_ = 0;

  auto result = kernel_streaming_backend_->initialize(config);
  AppendKernelStreamingEvents();
  if (result.ok) {
    result = kernel_streaming_backend_->start();
    AppendKernelStreamingEvents();
  }

  stats_ = kernel_streaming_backend_->getRealtimeStats();
  const auto events = kernel_streaming_backend_->diagnostic_events();
  RecordLastRun(config,
                FormatProbeForRun(config, selected_test_condition_, result.ok),
                events);
  last_pcm_summary_ = BuildPcmRunSummary(
      BackendApi::kKernelStreaming,
      config.device.stable_id,
      events,
      stats_);
  last_run_ok_ = result.ok;
  status_text_ =
      result.ok ? "Kernel Streaming running" : "Kernel Streaming error";
  if (!result.ok) {
    log_lines_.push_back(
        std::string(ks_data_range_candidate
                        ? "Kernel Streaming start verification failed: "
                        : "Kernel Streaming error: ") +
        result.error.message);
    kernel_streaming_backend_.reset();
    kernel_streaming_event_count_ = 0;
  }
}

void DiagnosticUiState::StartAsioPcm() {
  if (HasAnyActiveBackend()) {
    EnsureStartSafety("ASIO PCM start");
    return;
  }
  if (!selected_device_) {
    last_run_ok_ = false;
    status_text_ = "device not selected";
    log_lines_.push_back("ASIO start failed: no explicit ASIO driver selected");
    return;
  }
  if (!selected_playback_format_) {
    last_run_ok_ = false;
    status_text_ = "format not accepted";
    log_lines_.push_back("ASIO start failed: run selected-driver ASIO PCM probe first");
    return;
  }
  if (!selected_playback_backend_ ||
      *selected_playback_backend_ != BackendApi::kAsio) {
    last_run_ok_ = false;
    status_text_ = "ASIO format not accepted";
    log_lines_.push_back(
        "ASIO start failed: selected format was not accepted for ASIO");
    return;
  }
  if (!IsAsioPcmPlaybackFormat(*selected_playback_format_)) {
    last_run_ok_ = false;
    status_text_ = "use ASIO DoP button";
    log_lines_.push_back("ASIO PCM start failed: selected format is not PCM");
    return;
  }
  if (!EnsureStartSafety("ASIO PCM start")) {
    return;
  }

  PlaybackConfig config;
  config.backend = BackendApi::kAsio;
  config.device = *selected_device_;
  config.device.backend = BackendApi::kAsio;
  config.format = *selected_playback_format_;
  ApplySettingsToConfig(config);
  AppendRequestedSettingsLog(config, "ASIO PCM start");

  asio_backend_ = std::make_unique<AsioPcmBackend>();
  asio_event_count_ = 0;

  auto result = asio_backend_->initialize(config);
  AppendAsioEvents();
  if (result.ok) {
    result = asio_backend_->start();
    AppendAsioEvents();
  }

  stats_ = asio_backend_->getRealtimeStats();
  const auto events = asio_backend_->diagnostic_events();
  RecordLastRun(config,
                FormatProbeForRun(config, selected_test_condition_, result.ok),
                events);
  last_pcm_summary_ = BuildPcmRunSummary(
      BackendApi::kAsio,
      config.device.stable_id,
      events,
      stats_);
  last_run_ok_ = result.ok;
  status_text_ = result.ok ? "ASIO running" : "ASIO error";
  if (!result.ok) {
    log_lines_.push_back("ASIO error: " + result.error.message);
    asio_backend_.reset();
    asio_event_count_ = 0;
  }
}

void DiagnosticUiState::StartAsioDop() {
  if (HasAnyActiveBackend()) {
    EnsureStartSafety("ASIO DoP start");
    return;
  }
  if (!selected_device_) {
    last_run_ok_ = false;
    status_text_ = "device not selected";
    log_lines_.push_back("ASIO DoP start failed: no explicit ASIO driver selected");
    return;
  }
  if (!selected_playback_format_) {
    last_run_ok_ = false;
    status_text_ = "DoP carrier not accepted";
    log_lines_.push_back(
        "ASIO DoP start failed: run selected-driver ASIO DoP probe first");
    return;
  }
  if (!selected_playback_backend_ ||
      *selected_playback_backend_ != BackendApi::kAsio) {
    last_run_ok_ = false;
    status_text_ = "ASIO DoP carrier not accepted";
    log_lines_.push_back(
        "ASIO DoP start failed: selected format was not accepted for ASIO");
    return;
  }
  if (!IsAsioDopCarrierFormat(*selected_playback_format_)) {
    last_run_ok_ = false;
    status_text_ = "ASIO DoP carrier not accepted";
    log_lines_.push_back(
        "ASIO DoP start failed: selected format is not an exact DoP carrier");
    return;
  }
  if (!EnsureStartSafety("ASIO DoP start")) {
    return;
  }

  PlaybackConfig config;
  config.backend = BackendApi::kAsio;
  config.device = *selected_device_;
  config.device.backend = BackendApi::kAsio;
  config.format = *selected_playback_format_;
  ApplySettingsToConfig(config);
  AppendRequestedSettingsLog(config, "ASIO DoP start");

  asio_backend_ = std::make_unique<AsioPcmBackend>();
  asio_event_count_ = 0;

  auto result = asio_backend_->initialize(config);
  AppendAsioEvents();
  if (result.ok) {
    result = asio_backend_->start();
    AppendAsioEvents();
  }

  stats_ = asio_backend_->getRealtimeStats();
  const auto events = asio_backend_->diagnostic_events();
  RecordLastRun(config,
                FormatProbeForRun(config, selected_test_condition_, result.ok),
                events);
  last_pcm_summary_ = BuildPcmRunSummary(
      BackendApi::kAsio,
      config.device.stable_id,
      events,
      stats_);
  last_run_ok_ = result.ok;
  status_text_ = result.ok ? "ASIO DoP running" : "ASIO DoP error";
  if (!result.ok) {
    log_lines_.push_back("ASIO DoP error: " + result.error.message);
    asio_backend_.reset();
    asio_event_count_ = 0;
  }
}

void DiagnosticUiState::StartAsioNativeDsd() {
  if (HasAnyActiveBackend()) {
    EnsureStartSafety("ASIO native DSD start");
    return;
  }
  if (!selected_device_) {
    last_run_ok_ = false;
    status_text_ = "device not selected";
    log_lines_.push_back(
        "ASIO native DSD start failed: no explicit ASIO driver selected");
    return;
  }
  if (!selected_playback_format_) {
    last_run_ok_ = false;
    status_text_ = "format not accepted";
    log_lines_.push_back(
        "ASIO native DSD start failed: run selected-driver native DSD probe first");
    return;
  }
  if (!selected_playback_backend_ ||
      *selected_playback_backend_ != BackendApi::kAsio) {
    last_run_ok_ = false;
    status_text_ = "ASIO DSD format not accepted";
    log_lines_.push_back(
        "ASIO native DSD start failed: selected format was not accepted for ASIO");
    return;
  }
  if (!IsAsioNativeDsdPlaybackFormat(*selected_playback_format_)) {
    last_run_ok_ = false;
    status_text_ = "ASIO DSD format not accepted";
    log_lines_.push_back(
        "ASIO native DSD start failed: selected format is not native DSD");
    return;
  }
  if (settings_.high_load_diagnostics_enabled) {
    last_run_ok_ = false;
    status_text_ = "high-load unsupported for ASIO native DSD";
    log_lines_.push_back(
        "ASIO native DSD start blocked: high-load diagnostics are not implemented for native DSD");
    return;
  }
  if (!EnsureStartSafety("ASIO native DSD start")) {
    return;
  }

  PlaybackConfig config;
  config.backend = BackendApi::kAsio;
  config.device = *selected_device_;
  config.device.backend = BackendApi::kAsio;
  config.format = *selected_playback_format_;
  ApplySettingsToConfig(config);
  AppendRequestedSettingsLog(config, "ASIO native DSD start");

  asio_native_dsd_backend_ = std::make_unique<AsioNativeDsdBackend>();
  asio_native_dsd_event_count_ = 0;

  auto result = asio_native_dsd_backend_->initialize(config);
  AppendAsioNativeDsdEvents();
  if (result.ok) {
    result = asio_native_dsd_backend_->start();
    AppendAsioNativeDsdEvents();
  }

  stats_ = asio_native_dsd_backend_->getRealtimeStats();
  const auto events = asio_native_dsd_backend_->diagnostic_events();
  RecordLastRun(config,
                FormatProbeForRun(config, selected_test_condition_, result.ok),
                events);
  last_run_ok_ = result.ok;
  status_text_ = result.ok ? "ASIO native DSD running" : "ASIO native DSD error";
  if (!result.ok) {
    log_lines_.push_back("ASIO native DSD error: " + result.error.message);
    asio_native_dsd_backend_.reset();
    asio_native_dsd_event_count_ = 0;
  }
}

void DiagnosticUiState::StartWasapiExclusivePcm() {
  if (HasAnyActiveBackend()) {
    EnsureStartSafety("WASAPI exclusive start");
    return;
  }
  if (!selected_device_) {
    last_run_ok_ = false;
    status_text_ = "device not selected";
    log_lines_.push_back("WASAPI exclusive start failed: no explicit endpoint selected");
    return;
  }
  if (!selected_playback_format_) {
    last_run_ok_ = false;
    status_text_ = "format not accepted";
    log_lines_.push_back(
        "WASAPI exclusive start failed: run selected-endpoint exclusive format probe first");
    return;
  }
  if (!selected_playback_backend_ ||
      *selected_playback_backend_ != BackendApi::kWasapiExclusive) {
    last_run_ok_ = false;
    status_text_ = "exclusive format not accepted";
    log_lines_.push_back(
        "WASAPI exclusive start failed: selected format was not accepted for exclusive mode");
    return;
  }
  if (selected_playback_format_->signal_mode != SignalMode::kPcm) {
    last_run_ok_ = false;
    status_text_ = "use DoP button";
    log_lines_.push_back(
        "WASAPI exclusive PCM start failed: selected format is not PCM");
    return;
  }
  if (!EnsureStartSafety("WASAPI exclusive start")) {
    return;
  }

  PlaybackConfig config;
  config.backend = BackendApi::kWasapiExclusive;
  config.device = *selected_device_;
  config.device.backend = BackendApi::kWasapiExclusive;
  config.format = *selected_playback_format_;
  ApplySettingsToConfig(config);
  AppendRequestedSettingsLog(config, "WASAPI exclusive start");

  wasapi_exclusive_backend_ = std::make_unique<WasapiExclusivePcmBackend>();
  wasapi_exclusive_event_count_ = 0;

  auto result = wasapi_exclusive_backend_->initialize(config);
  AppendWasapiExclusiveEvents();
  if (result.ok) {
    result = wasapi_exclusive_backend_->start();
    AppendWasapiExclusiveEvents();
  }

  stats_ = wasapi_exclusive_backend_->getRealtimeStats();
  const auto events = wasapi_exclusive_backend_->diagnostic_events();
  RecordLastRun(config,
                FormatProbeForRun(config, selected_test_condition_, result.ok),
                events);
  last_pcm_summary_ = BuildPcmRunSummary(
      BackendApi::kWasapiExclusive,
      config.device.stable_id,
      events,
      stats_);
  last_run_ok_ = result.ok;
  status_text_ = result.ok ? "WASAPI exclusive running" : "WASAPI exclusive error";
  if (!result.ok) {
    log_lines_.push_back("WASAPI exclusive error: " + result.error.message);
  }
}

void DiagnosticUiState::StartWasapiExclusiveDop() {
  if (HasAnyActiveBackend()) {
    EnsureStartSafety("WASAPI DoP start");
    return;
  }
  if (!selected_device_) {
    last_run_ok_ = false;
    status_text_ = "device not selected";
    log_lines_.push_back("WASAPI DoP start failed: no explicit endpoint selected");
    return;
  }
  if (!selected_playback_format_) {
    last_run_ok_ = false;
    status_text_ = "DoP carrier not accepted";
    log_lines_.push_back(
        "WASAPI DoP start failed: run selected-endpoint DoP probe first");
    return;
  }
  if (!selected_playback_backend_ ||
      *selected_playback_backend_ != BackendApi::kWasapiExclusive) {
    last_run_ok_ = false;
    status_text_ = "DoP carrier not accepted";
    log_lines_.push_back(
        "WASAPI DoP start failed: selected format was not accepted for exclusive mode");
    return;
  }
  if (!IsWasapiExclusiveDopCarrierFormat(*selected_playback_format_)) {
    last_run_ok_ = false;
    status_text_ = "DoP carrier not accepted";
    log_lines_.push_back(
        "WASAPI DoP start failed: selected format is not an exact DoP carrier");
    return;
  }
  if (!EnsureStartSafety("WASAPI DoP start")) {
    return;
  }

  PlaybackConfig config;
  config.backend = BackendApi::kWasapiExclusive;
  config.device = *selected_device_;
  config.device.backend = BackendApi::kWasapiExclusive;
  config.format = *selected_playback_format_;
  ApplySettingsToConfig(config);
  AppendRequestedSettingsLog(config, "WASAPI DoP start");

  wasapi_exclusive_backend_ = std::make_unique<WasapiExclusivePcmBackend>();
  wasapi_exclusive_event_count_ = 0;

  auto result = wasapi_exclusive_backend_->initialize(config);
  AppendWasapiExclusiveEvents();
  if (result.ok) {
    result = wasapi_exclusive_backend_->start();
    AppendWasapiExclusiveEvents();
  }

  stats_ = wasapi_exclusive_backend_->getRealtimeStats();
  const auto events = wasapi_exclusive_backend_->diagnostic_events();
  RecordLastRun(config,
                FormatProbeForRun(config, selected_test_condition_, result.ok),
                events);
  last_pcm_summary_ = BuildPcmRunSummary(
      BackendApi::kWasapiExclusive,
      config.device.stable_id,
      events,
      stats_);
  last_run_ok_ = result.ok;
  status_text_ = result.ok ? "WASAPI DoP running" : "WASAPI DoP error";
  if (!result.ok) {
    log_lines_.push_back("WASAPI DoP error: " + result.error.message);
  }
}

void DiagnosticUiState::StopDirectSoundPcm() {
  if (!directsound_backend_) {
    last_run_ok_ = false;
    status_text_ = "DirectSound not running";
    log_lines_.push_back("DirectSound stop ignored: backend is not active");
    return;
  }

  const auto result = directsound_backend_->stop();
  AppendDirectSoundEvents();
  stats_ = directsound_backend_->getRealtimeStats();
  const auto events = directsound_backend_->diagnostic_events();
  RecordLastEvents(events);
  last_pcm_summary_ = BuildPcmRunSummary(
      BackendApi::kDirectSound,
      events.empty()
          ? ""
          : events.front().device_id,
      events,
      stats_);
  last_run_ok_ = result.ok;
  status_text_ = result.ok ? "DirectSound keep-warm" : "DirectSound error";
  if (!result.ok) {
    log_lines_.push_back("DirectSound stop error: " + result.error.message);
  }
}

void DiagnosticUiState::StopAsioPcm() {
  if (!asio_backend_) {
    last_run_ok_ = false;
    status_text_ = "ASIO not running";
    log_lines_.push_back("ASIO stop ignored: backend is not active");
    return;
  }

  const auto result = asio_backend_->stop();
  AppendAsioEvents();
  stats_ = asio_backend_->getRealtimeStats();
  const auto events = asio_backend_->diagnostic_events();
  RecordLastEvents(events);
  last_pcm_summary_ = BuildPcmRunSummary(
      BackendApi::kAsio,
      events.empty()
          ? ""
          : events.front().device_id,
      events,
      stats_);
  last_run_ok_ = result.ok;
  status_text_ = result.ok ? "ASIO keep-warm" : "ASIO error";
  if (!result.ok) {
    log_lines_.push_back("ASIO stop error: " + result.error.message);
  }
}

void DiagnosticUiState::StopAsioNativeDsd() {
  if (!asio_native_dsd_backend_) {
    last_run_ok_ = false;
    status_text_ = "ASIO native DSD not running";
    log_lines_.push_back("ASIO native DSD stop ignored: backend is not active");
    return;
  }

  const auto result = asio_native_dsd_backend_->stop();
  AppendAsioNativeDsdEvents();
  stats_ = asio_native_dsd_backend_->getRealtimeStats();
  RecordLastEvents(asio_native_dsd_backend_->diagnostic_events());
  last_run_ok_ = result.ok;
  status_text_ = result.ok ? "ASIO native DSD keep-warm" : "ASIO native DSD error";
  if (!result.ok) {
    log_lines_.push_back("ASIO native DSD stop error: " + result.error.message);
  }
}

void DiagnosticUiState::StopMmePcm() {
  if (!mme_backend_) {
    last_run_ok_ = false;
    status_text_ = "MME not running";
    log_lines_.push_back("MME stop ignored: backend is not active");
    return;
  }

  const auto result = mme_backend_->stop();
  AppendMmeEvents();
  stats_ = mme_backend_->getRealtimeStats();
  const auto events = mme_backend_->diagnostic_events();
  RecordLastEvents(events);
  last_pcm_summary_ = BuildPcmRunSummary(
      BackendApi::kMme,
      events.empty()
          ? ""
          : events.front().device_id,
      events,
      stats_);
  last_run_ok_ = result.ok;
  status_text_ = result.ok ? "MME keep-warm" : "MME error";
  if (!result.ok) {
    log_lines_.push_back("MME stop error: " + result.error.message);
  }
}

void DiagnosticUiState::StopWasapiSharedPcm() {
  if (!wasapi_shared_backend_) {
    last_run_ok_ = false;
    status_text_ = "WASAPI shared not running";
    log_lines_.push_back("WASAPI shared stop ignored: backend is not active");
    return;
  }

  const auto result = wasapi_shared_backend_->stop();
  AppendWasapiSharedEvents();
  stats_ = wasapi_shared_backend_->getRealtimeStats();
  const auto events = wasapi_shared_backend_->diagnostic_events();
  RecordLastEvents(events);
  last_pcm_summary_ = BuildPcmRunSummary(
      BackendApi::kWasapiShared,
      events.empty()
          ? ""
          : events.front().device_id,
      events,
      stats_);
  last_run_ok_ = result.ok;
  status_text_ = result.ok ? "WASAPI shared keep-warm" : "WASAPI shared error";
  if (!result.ok) {
    log_lines_.push_back("WASAPI shared stop error: " + result.error.message);
  }
}

void DiagnosticUiState::StopWasapiExclusivePcm() {
  if (!wasapi_exclusive_backend_) {
    last_run_ok_ = false;
    status_text_ = "WASAPI exclusive not running";
    log_lines_.push_back("WASAPI exclusive stop ignored: backend is not active");
    return;
  }

  const auto result = wasapi_exclusive_backend_->stop();
  AppendWasapiExclusiveEvents();
  stats_ = wasapi_exclusive_backend_->getRealtimeStats();
  const auto events = wasapi_exclusive_backend_->diagnostic_events();
  RecordLastEvents(events);
  last_pcm_summary_ = BuildPcmRunSummary(
      BackendApi::kWasapiExclusive,
      events.empty()
          ? ""
          : events.front().device_id,
      events,
      stats_);
  last_run_ok_ = result.ok;
  status_text_ = result.ok ? "WASAPI exclusive keep-warm" : "WASAPI exclusive error";
  if (!result.ok) {
    log_lines_.push_back("WASAPI exclusive stop error: " + result.error.message);
  }
}

void DiagnosticUiState::StopKernelStreamingPcm() {
  if (!kernel_streaming_backend_) {
    last_run_ok_ = false;
    status_text_ = "Kernel Streaming not running";
    log_lines_.push_back(
        "Kernel Streaming stop ignored: backend is not active");
    return;
  }

  const auto result = kernel_streaming_backend_->stop();
  AppendKernelStreamingEvents();
  stats_ = kernel_streaming_backend_->getRealtimeStats();
  const auto events = kernel_streaming_backend_->diagnostic_events();
  RecordLastEvents(events);
  last_pcm_summary_ = BuildPcmRunSummary(
      BackendApi::kKernelStreaming,
      events.empty()
          ? ""
          : events.front().device_id,
      events,
      stats_);
  last_run_ok_ = result.ok;
  status_text_ =
      result.ok ? "Kernel Streaming keep-warm" : "Kernel Streaming error";
  if (!result.ok) {
    log_lines_.push_back(
        "Kernel Streaming stop error: " + result.error.message);
  }
}

void DiagnosticUiState::ReleaseDirectSoundPcm() {
  if (!directsound_backend_) {
    last_run_ok_ = false;
    status_text_ = "DirectSound not active";
    log_lines_.push_back("DirectSound release ignored: backend is not active");
    return;
  }

  const auto result = directsound_backend_->shutdown();
  AppendDirectSoundEvents();
  stats_ = directsound_backend_->getRealtimeStats();
  const auto events = directsound_backend_->diagnostic_events();
  RecordLastEvents(events);
  last_pcm_summary_ = BuildPcmRunSummary(
      BackendApi::kDirectSound,
      events.empty()
          ? ""
          : events.front().device_id,
      events,
      stats_);
  last_run_ok_ = result.ok;
  status_text_ = result.ok ? "DirectSound released" : "DirectSound error";
  RecordReleaseResult(BackendApi::kDirectSound, result);
  if (!result.ok) {
    log_lines_.push_back("DirectSound release error: " + result.error.message);
    log_lines_.push_back(
        "DirectSound release retained backend state so the user can retry release");
    return;
  }
  directsound_backend_.reset();
  directsound_event_count_ = 0;
}

void DiagnosticUiState::ReleaseAsioPcm() {
  if (!asio_backend_) {
    last_run_ok_ = false;
    status_text_ = "ASIO not active";
    log_lines_.push_back("ASIO release ignored: backend is not active");
    return;
  }

  const auto result = asio_backend_->shutdown();
  AppendAsioEvents();
  stats_ = asio_backend_->getRealtimeStats();
  const auto events = asio_backend_->diagnostic_events();
  RecordLastEvents(events);
  last_pcm_summary_ = BuildPcmRunSummary(
      BackendApi::kAsio,
      events.empty()
          ? ""
          : events.front().device_id,
      events,
      stats_);
  last_run_ok_ = result.ok;
  status_text_ = result.ok ? "ASIO released" : "ASIO error";
  RecordReleaseResult(BackendApi::kAsio, result);
  if (!result.ok) {
    log_lines_.push_back("ASIO release error: " + result.error.message);
    log_lines_.push_back(
        "ASIO release retained backend state so the user can retry release");
    return;
  }
  asio_backend_.reset();
  asio_event_count_ = 0;
}

void DiagnosticUiState::ReleaseAsioNativeDsd() {
  if (!asio_native_dsd_backend_) {
    last_run_ok_ = false;
    status_text_ = "ASIO native DSD not active";
    log_lines_.push_back("ASIO native DSD release ignored: backend is not active");
    return;
  }

  const auto result = asio_native_dsd_backend_->shutdown();
  AppendAsioNativeDsdEvents();
  stats_ = asio_native_dsd_backend_->getRealtimeStats();
  RecordLastEvents(asio_native_dsd_backend_->diagnostic_events());
  last_run_ok_ = result.ok;
  status_text_ = result.ok ? "ASIO native DSD released" : "ASIO native DSD error";
  RecordReleaseResult(BackendApi::kAsio, result);
  if (!result.ok) {
    log_lines_.push_back("ASIO native DSD release error: " + result.error.message);
    log_lines_.push_back(
        "ASIO native DSD release retained backend state so the user can retry release");
    return;
  }
  asio_native_dsd_backend_.reset();
  asio_native_dsd_event_count_ = 0;
}

void DiagnosticUiState::ReleaseMmePcm() {
  if (!mme_backend_) {
    last_run_ok_ = false;
    status_text_ = "MME not active";
    log_lines_.push_back("MME release ignored: backend is not active");
    return;
  }

  const auto result = mme_backend_->shutdown();
  AppendMmeEvents();
  stats_ = mme_backend_->getRealtimeStats();
  const auto events = mme_backend_->diagnostic_events();
  RecordLastEvents(events);
  last_pcm_summary_ = BuildPcmRunSummary(
      BackendApi::kMme,
      events.empty()
          ? ""
          : events.front().device_id,
      events,
      stats_);
  last_run_ok_ = result.ok;
  status_text_ = result.ok ? "MME released" : "MME error";
  RecordReleaseResult(BackendApi::kMme, result);
  if (!result.ok) {
    log_lines_.push_back("MME release error: " + result.error.message);
    log_lines_.push_back(
        "MME release retained backend state so the user can retry release");
    return;
  }
  mme_backend_.reset();
  mme_event_count_ = 0;
}

void DiagnosticUiState::ReleaseWasapiSharedPcm() {
  if (!wasapi_shared_backend_) {
    last_run_ok_ = false;
    status_text_ = "WASAPI shared not active";
    log_lines_.push_back("WASAPI shared release ignored: backend is not active");
    return;
  }

  const auto result = wasapi_shared_backend_->shutdown();
  AppendWasapiSharedEvents();
  stats_ = wasapi_shared_backend_->getRealtimeStats();
  const auto events = wasapi_shared_backend_->diagnostic_events();
  RecordLastEvents(events);
  last_pcm_summary_ = BuildPcmRunSummary(
      BackendApi::kWasapiShared,
      events.empty()
          ? ""
          : events.front().device_id,
      events,
      stats_);
  last_run_ok_ = result.ok;
  status_text_ = result.ok ? "WASAPI shared released" : "WASAPI shared error";
  RecordReleaseResult(BackendApi::kWasapiShared, result);
  if (!result.ok) {
    log_lines_.push_back("WASAPI shared release error: " + result.error.message);
    log_lines_.push_back(
        "WASAPI shared release retained backend state so the user can retry "
        "release");
    return;
  }
  wasapi_shared_backend_.reset();
  wasapi_shared_event_count_ = 0;
}

void DiagnosticUiState::ReleaseWasapiExclusivePcm() {
  if (!wasapi_exclusive_backend_) {
    last_run_ok_ = false;
    status_text_ = "WASAPI exclusive not active";
    log_lines_.push_back("WASAPI exclusive release ignored: backend is not active");
    return;
  }

  const auto result = wasapi_exclusive_backend_->shutdown();
  AppendWasapiExclusiveEvents();
  stats_ = wasapi_exclusive_backend_->getRealtimeStats();
  const auto events = wasapi_exclusive_backend_->diagnostic_events();
  RecordLastEvents(events);
  last_pcm_summary_ = BuildPcmRunSummary(
      BackendApi::kWasapiExclusive,
      events.empty()
          ? ""
          : events.front().device_id,
      events,
      stats_);
  last_run_ok_ = result.ok;
  status_text_ = result.ok ? "WASAPI exclusive released" : "WASAPI exclusive error";
  RecordReleaseResult(BackendApi::kWasapiExclusive, result);
  if (!result.ok) {
    log_lines_.push_back("WASAPI exclusive release error: " + result.error.message);
    log_lines_.push_back(
        "WASAPI exclusive release retained backend state so the user can retry "
        "release");
    return;
  }
  wasapi_exclusive_backend_.reset();
  wasapi_exclusive_event_count_ = 0;
}

void DiagnosticUiState::ReleaseKernelStreamingPcm() {
  if (!kernel_streaming_backend_) {
    last_run_ok_ = false;
    status_text_ = "Kernel Streaming not active";
    log_lines_.push_back(
        "Kernel Streaming release ignored: backend is not active");
    return;
  }

  const auto result = kernel_streaming_backend_->shutdown();
  AppendKernelStreamingEvents();
  stats_ = kernel_streaming_backend_->getRealtimeStats();
  const auto events = kernel_streaming_backend_->diagnostic_events();
  RecordLastEvents(events);
  last_pcm_summary_ = BuildPcmRunSummary(
      BackendApi::kKernelStreaming,
      events.empty()
          ? ""
          : events.front().device_id,
      events,
      stats_);
  last_run_ok_ = result.ok;
  status_text_ =
      result.ok ? "Kernel Streaming released" : "Kernel Streaming error";
  RecordReleaseResult(BackendApi::kKernelStreaming, result);
  if (!result.ok) {
    log_lines_.push_back(
        "Kernel Streaming release error: " + result.error.message);
    log_lines_.push_back(
        "Kernel Streaming release retained backend state so the user can retry release");
    return;
  }
  kernel_streaming_backend_.reset();
  kernel_streaming_event_count_ = 0;
}

bool DiagnosticUiState::SelectDiscoveredDeviceById(const std::string& stable_id) {
  if (HasAnyActiveBackend()) {
    if (selected_device_ && selected_device_->stable_id == stable_id) {
      log_lines_.push_back(
          "selection unchanged: active backend is using the selected device");
      return true;
    }
    last_run_ok_ = false;
    status_text_ = "active backend locked";
    log_lines_.push_back(
        "device selection blocked: " +
        std::string(kActiveBackendInterlockReason));
    return false;
  }

  const auto selected = FindDeviceByStableId(discovery_snapshot_, stable_id);
  if (!selected) {
    selected_device_.reset();
    ResetAcceptedFormatSelection();
    ClearDeviceCapabilityMatrix();
    last_run_ok_ = false;
    status_text_ = "device not found";
    log_lines_.push_back("selection failed: " + stable_id);
    return false;
  }
  if (!DeviceMatchesRequestedBackend(selected->device,
                                     settings_.requested_backend)) {
    selected_device_.reset();
    ResetAcceptedFormatSelection();
    ClearDeviceCapabilityMatrix();
    last_run_ok_ = false;
    status_text_ = "backend mismatch";
    log_lines_.push_back(
        "selection failed: selected device does not belong to the current target API");
    return false;
  }

  selected_device_ = selected->device;
  ResetAcceptedFormatSelection();
  ClearDeviceCapabilityMatrix();
  bundle_path_.reset();
  last_pcm_summary_.reset();
  last_playback_config_.reset();
  last_format_probe_ = FormatProbeResult{};
  last_probe_has_format_rows_ = false;
  last_diagnostic_events_.clear();
  last_automatic_plan_.reset();
  last_diagnostic_score_.reset();
  bool captured_requested_probe = false;
  for (const auto& probe : selected->probes) {
    if (probe.kind == CapabilityProbeKind::kFormatSupport) {
      last_probe_has_format_rows_ = true;
      if (probe.requested_format && !captured_requested_probe) {
        last_format_probe_.requested = *probe.requested_format;
        captured_requested_probe = true;
      }
      if (IsConfirmedSupportedFormatProbe(selected->device.backend, probe)) {
        PushUniqueFormat(last_format_probe_.supported_formats,
                         *probe.accepted_format);
      } else if (selected->device.backend == BackendApi::kKernelStreaming &&
                 probe.support == CapabilitySupport::kSupported &&
                 probe.accepted_format &&
                 IsKernelStreamingDataRangeOnlyCandidate(probe)) {
        last_format_probe_.rejection_reasons.push_back(
            CandidateOnlyReason(probe));
      } else if (!probe.detail.empty()) {
        last_format_probe_.rejection_reasons.push_back(probe.detail);
      }
    }
  }
  AutoSelectExactRequestedFormatFromSelectedSnapshot();
  if (!captured_requested_probe && selected_playback_format_) {
    last_format_probe_.requested = *selected_playback_format_;
  }
  last_run_ok_ = true;
  status_text_ = "device selected";
  log_lines_.push_back("selected device: " + selected->device.stable_id);
  if (!selected_playback_format_) {
    log_lines_.push_back(
        "no exact requested format was auto-selected; use an accepted probe row explicitly for fallback, mix, or closest-match formats");
  }
  return true;
}

void DiagnosticUiState::BuildDeviceCapabilityMatrix() {
  if (RejectIfActive("capability matrix build")) {
    return;
  }
  if (!selected_device_) {
    last_run_ok_ = false;
    status_text_ = "device not selected";
    log_lines_.push_back(
        "capability matrix build failed: select a target device first");
    return;
  }
  if (!DeviceMatchesRequestedBackend(*selected_device_,
                                     settings_.requested_backend)) {
    last_run_ok_ = false;
    status_text_ = "backend mismatch";
    log_lines_.push_back(
        "capability matrix build failed: selected device does not belong to the current target API; reload devices for the selected API");
    return;
  }

  ResetAcceptedFormatSelection();

  DeviceCapabilityMatrix matrix;
  matrix.target_device_group_id = selected_device_->stable_id;
  matrix.target_backend = settings_.requested_backend;
  matrix.scan_revision = ++capability_matrix_revision_;
  const auto probe_candidate_rows = CapabilityMatrixRows();
  matrix.rows = probe_candidate_rows;
  matrix.sample_rate_columns = CapabilityMatrixSampleRateColumns();

  std::vector<DeviceCapabilitySnapshot> evidence_snapshots;
  const auto existing_selected_snapshot = FindDeviceByStableId(
      discovery_snapshot_,
      selected_device_->stable_id);
  if (existing_selected_snapshot &&
      existing_selected_snapshot->device.backend == matrix.target_backend &&
      SnapshotHasFormatProbeRows(*existing_selected_snapshot) &&
      ProbeRowsAreFreshForCurrentFormat()) {
    evidence_snapshots.push_back(*existing_selected_snapshot);
  }
  std::vector<DeviceCapabilitySnapshot> probed_snapshots;
  if (!FindMatrixEvidenceSnapshot(evidence_snapshots,
                                  selected_device_->stable_id,
                                  matrix.target_backend)) {
    probed_snapshots = ProbeMatrixCapabilities(*selected_device_,
                                               probe_candidate_rows,
                                               matrix.sample_rate_columns,
                                               matrix.target_backend,
                                               settings_);
  }
  evidence_snapshots.insert(evidence_snapshots.end(),
                            std::make_move_iterator(probed_snapshots.begin()),
                            std::make_move_iterator(probed_snapshots.end()));

  for (std::size_t row_index = 0; row_index < matrix.rows.size();
       ++row_index) {
    const auto& row_format = matrix.rows[row_index];
    for (const auto sample_rate_hz : matrix.sample_rate_columns) {
      CapabilityCell cell;
      const BackendApi backend = matrix.target_backend;
      const auto requested_format =
          MatrixFormatForCell(row_format, sample_rate_hz);
      cell.backend = backend;
      cell.requested_format = requested_format.value_or(row_format);
      cell.requested_format.sample_rate_hz = sample_rate_hz;

      if (!requested_format) {
        cell.result_status = CapabilityCellStatus::kNotApplicable;
        cell.disabled_reason =
            "this sample rate is not valid for this row format";
        matrix.cells.push_back(std::move(cell));
        continue;
      }

      if (!IsBackendFormatCombinationApplicable(backend, *requested_format)) {
        cell.result_status = CapabilityCellStatus::kNotApplicable;
        cell.disabled_reason =
            "format is not valid for this backend/API path";
        matrix.cells.push_back(std::move(cell));
        continue;
      }

      if (backend == BackendApi::kAsio && !IsAsioSdkEnabled()) {
        cell.result_status = CapabilityCellStatus::kNotApplicable;
        cell.disabled_reason = "ASIO support is disabled in this build";
        matrix.cells.push_back(std::move(cell));
        continue;
      }

      if (!CanMapSelectedDeviceToBackend(*selected_device_, backend)) {
        cell.result_status = CapabilityCellStatus::kNotApplicable;
        cell.disabled_reason =
            "this API path is not currently mapped to the selected target device";
        matrix.cells.push_back(std::move(cell));
        continue;
      }

      const auto mapped_device =
          MatrixDeviceForBackend(*selected_device_, backend);
      cell.backend_device_id = mapped_device.stable_id;
      cell.backend_device_name = mapped_device.display_name;

      bool found_probe = false;
      const auto evidence_snapshot = FindMatrixEvidenceSnapshot(
          evidence_snapshots,
          mapped_device.stable_id,
          backend);
      if (evidence_snapshot) {
        int best_probe_priority = -1;
        std::optional<std::size_t> best_probe_index;
        for (std::size_t probe_index = 0;
             probe_index < evidence_snapshot->probes.size();
             ++probe_index) {
          const auto& probe = evidence_snapshot->probes[probe_index];
          const auto priority =
              MatrixProbePriority(backend, *requested_format, probe);
          if (priority > best_probe_priority) {
            best_probe_priority = priority;
            best_probe_index = probe_index;
          }
        }
        if (best_probe_index) {
          const auto probe_index = *best_probe_index;
          const auto& probe = evidence_snapshot->probes[probe_index];
          found_probe = true;
          cell.probe_index = probe_index;
          cell.accepted_format = probe.accepted_format;
          cell.result_status =
              ProbeStatusForMatrixCell(backend, *requested_format, probe);
          cell.reference_only = IsMixFormatProbe(probe);
          cell.selection_kind =
              SelectionKindForProbe(probe, *requested_format);
          cell.stale = false;
          cell.raw_backend_fields = probe.backend_fields;
          if (probe.error) {
            cell.error_symbol = probe.error->symbol;
            cell.error_code_hex = probe.error->raw_code_hex;
          }
          if (!probe.detail.empty()) {
            cell.warning_flags.push_back(probe.detail);
          }
          if (cell.stale) {
            cell.disabled_reason = "capability result is stale; scan again";
          } else if (cell.reference_only) {
            cell.disabled_reason =
                "reference-only row; not selectable for playback";
          } else if (backend == BackendApi::kKernelStreaming &&
                     cell.result_status == CapabilityCellStatus::kWarning &&
                     cell.raw_backend_fields["ks_playback_implementation"] ==
                         "unimplemented") {
            cell.disabled_reason =
                "Kernel Streaming model detected but playback is not implemented for this model";
          } else if (!CapabilityStatusCanCreateTestCondition(
                         cell.result_status)) {
            cell.disabled_reason =
                "requested format is not available for this backend";
          } else if (!cell.accepted_format) {
            cell.disabled_reason = "no accepted playback format is available";
          } else if (!IsPlayableAcceptedFormatForBackend(
                         backend,
                         *cell.accepted_format,
                         probe)) {
            cell.disabled_reason =
                "accepted format is not playable for this backend";
          } else {
            cell.selectable = true;
          }
        }
      }

      if (!found_probe) {
        if (evidence_snapshot && evidence_snapshot->discovery_error) {
          cell.result_status = CapabilityCellStatus::kError;
          cell.disabled_reason = evidence_snapshot->discovery_error->message;
          cell.error_symbol = evidence_snapshot->discovery_error->symbol;
          cell.error_code_hex = evidence_snapshot->discovery_error->raw_code_hex;
        } else {
          cell.result_status = CapabilityCellStatus::kUnchecked;
          cell.disabled_reason =
              "no current capability result is available for this cell";
        }
      }

      matrix.cells.push_back(std::move(cell));
    }
  }

  device_capability_matrix_ = std::move(matrix);
  last_run_ok_ = true;
  status_text_ = "capability matrix ready";
  std::ostringstream line;
  line << "capability matrix built: target=" << selected_device_->stable_id
       << " backend=" << ToString(matrix.target_backend)
       << " probe_candidate_rows=" << probe_candidate_rows.size()
       << " rows=" << device_capability_matrix_->rows.size()
       << " sample_rate_columns="
       << device_capability_matrix_->sample_rate_columns.size()
       << " evidence_snapshots=" << evidence_snapshots.size()
       << " starts_stream=false";
  log_lines_.push_back(line.str());
}

bool DiagnosticUiState::SelectCapabilityMatrixCell(
    std::size_t row_index,
    std::size_t column_index) {
  if (RejectIfActive("capability matrix selection")) {
    return false;
  }
  if (!device_capability_matrix_) {
    last_run_ok_ = false;
    status_text_ = "capability matrix missing";
    log_lines_.push_back(
        "capability matrix selection failed: build a matrix first");
    return false;
  }
  auto& matrix = *device_capability_matrix_;
  if (matrix.stale) {
    last_run_ok_ = false;
    status_text_ = "capability matrix stale";
    log_lines_.push_back(
        "capability matrix selection failed: matrix is stale");
    return false;
  }
  if (row_index >= matrix.rows.size() ||
      column_index >= matrix.sample_rate_columns.size()) {
    last_run_ok_ = false;
    status_text_ = "matrix cell not found";
    log_lines_.push_back(
        "capability matrix selection failed: cell index is out of range");
    return false;
  }
  const auto cell_index =
      row_index * matrix.sample_rate_columns.size() + column_index;
  if (cell_index >= matrix.cells.size()) {
    last_run_ok_ = false;
    status_text_ = "matrix cell not found";
    log_lines_.push_back(
        "capability matrix selection failed: cell storage is incomplete");
    return false;
  }
  const auto& cell = matrix.cells[cell_index];
  if (!cell.selectable || !cell.accepted_format || cell.stale ||
      cell.reference_only) {
    last_run_ok_ = false;
    status_text_ = "matrix cell unavailable";
    std::ostringstream line;
    line << "capability matrix selection failed: status="
         << ToString(cell.result_status);
    if (!cell.disabled_reason.empty()) {
      line << " reason=" << cell.disabled_reason;
    }
    log_lines_.push_back(line.str());
    return false;
  }

  DiagnosticUiSettings selected_settings = settings_;
  ApplyFormatToSettings(*cell.accepted_format, cell.backend, selected_settings);
  const bool format_settings_changed =
      IsFormatChangingSettingDifferent(settings_, selected_settings);
  settings_ = std::move(selected_settings);
  if (format_settings_changed) {
    ++format_revision_;
  }

  if (selected_device_) {
    selected_device_ = MatrixDeviceForBackend(*selected_device_, cell.backend);
  }
  AcceptPlaybackFormat(*cell.accepted_format,
                       cell.backend,
                       MatrixSelectionKindForCell(cell),
                       "capability matrix cell selection");
  StoreSelectedTestCondition(cell.backend,
                             cell.requested_format,
                             *cell.accepted_format,
                             matrix.scan_revision,
                             row_index,
                             column_index,
                             cell.backend_device_id,
                             cell.backend_device_name,
                             cell.result_status,
                             cell.raw_backend_fields);
  last_run_ok_ = true;
  status_text_ = "test condition selected";
  return true;
}

bool DiagnosticUiState::SelectAcceptedFormatFromProbeIndex(
    std::size_t probe_index) {
  if (RejectIfActive("accepted format selection")) {
    return false;
  }
  if (RejectIfProbeRowsStale("accepted format selection")) {
    return false;
  }
  if (!selected_device_) {
    last_run_ok_ = false;
    status_text_ = "device not selected";
    log_lines_.push_back(
        "accepted format selection failed: select a device first");
    return false;
  }
  const auto selected = FindDeviceByStableId(
      discovery_snapshot_,
      selected_device_->stable_id);
  if (!selected || probe_index >= selected->probes.size()) {
    last_run_ok_ = false;
    status_text_ = "probe row not found";
    log_lines_.push_back(
        "accepted format selection failed: probe row is not available");
    return false;
  }

  const auto& probe = selected->probes[probe_index];
  if (probe.kind != CapabilityProbeKind::kFormatSupport ||
      !probe.accepted_format) {
    last_run_ok_ = false;
    status_text_ = "format not accepted";
    log_lines_.push_back(
        "accepted format selection failed: probe row has no accepted format");
    return false;
  }
  if (IsMixFormatProbe(probe)) {
    last_run_ok_ = false;
    status_text_ = "mix format reference";
    log_lines_.push_back(
        "accepted format selection failed: GetMixFormat reference row is not playable; use an IsFormatSupported row");
    return false;
  }
  const BackendApi acceptance_backend = selected_device_->backend;
  if (acceptance_backend != settings_.requested_backend) {
    last_run_ok_ = false;
    status_text_ = "backend mismatch";
    log_lines_.push_back(
        "accepted format selection failed: selected device backend does not match the requested backend");
    return false;
  }
  const bool snapshot_backend_matches =
      selected->device.backend == acceptance_backend;
  if (!snapshot_backend_matches) {
    last_run_ok_ = false;
    status_text_ = "backend mismatch";
    log_lines_.push_back(
        "accepted format selection failed: probe row backend does not match the selected device backend");
    return false;
  }
  if (!IsPlayableAcceptedFormatForBackend(acceptance_backend,
                                          *probe.accepted_format,
                                          probe)) {
    last_run_ok_ = false;
    status_text_ = "format not accepted";
    log_lines_.push_back(
        "accepted format selection failed: selected row is not a playable format for this backend");
    return false;
  }

  const auto kind =
      SelectionKindForProbe(probe, requested_format_from_settings());
  AcceptPlaybackFormat(*probe.accepted_format,
                       acceptance_backend,
                       kind,
                       "explicit probe row selection");
  last_run_ok_ = true;
  status_text_ = "accepted format selected";
  return true;
}

void DiagnosticUiState::AppendAsioEvents() {
  if (!asio_backend_) {
    return;
  }

  const auto events = asio_backend_->diagnostic_events();
  for (std::size_t index = asio_event_count_; index < events.size(); ++index) {
    const auto& event = events[index];
    std::ostringstream line;
    line << '#' << event.sequence << ' ' << ToString(event.type) << ": "
         << event.message;
    if (event.lifecycle_to) {
      line << " -> " << ToString(*event.lifecycle_to);
    }
    log_lines_.push_back(line.str());
  }
  asio_event_count_ = events.size();
}

void DiagnosticUiState::AppendAsioNativeDsdEvents() {
  if (!asio_native_dsd_backend_) {
    return;
  }

  const auto events = asio_native_dsd_backend_->diagnostic_events();
  for (std::size_t index = asio_native_dsd_event_count_;
       index < events.size();
       ++index) {
    const auto& event = events[index];
    std::ostringstream line;
    line << '#' << event.sequence << ' ' << ToString(event.type) << ": "
         << event.message;
    if (event.lifecycle_to) {
      line << " -> " << ToString(*event.lifecycle_to);
    }
    log_lines_.push_back(line.str());
  }
  asio_native_dsd_event_count_ = events.size();
}

void DiagnosticUiState::AppendKernelStreamingEvents() {
  if (!kernel_streaming_backend_) {
    return;
  }

  const auto events = kernel_streaming_backend_->diagnostic_events();
  for (std::size_t index = kernel_streaming_event_count_; index < events.size();
       ++index) {
    const auto& event = events[index];
    std::ostringstream line;
    line << '#' << event.sequence << ' ' << ToString(event.type) << ": "
         << event.message;
    if (event.lifecycle_to) {
      line << " -> " << ToString(*event.lifecycle_to);
    }
    log_lines_.push_back(line.str());
  }
  kernel_streaming_event_count_ = events.size();
}

void DiagnosticUiState::AppendDirectSoundEvents() {
  if (!directsound_backend_) {
    return;
  }

  const auto events = directsound_backend_->diagnostic_events();
  for (std::size_t index = directsound_event_count_; index < events.size(); ++index) {
    const auto& event = events[index];
    std::ostringstream line;
    line << '#' << event.sequence << ' ' << ToString(event.type) << ": "
         << event.message;
    if (event.lifecycle_to) {
      line << " -> " << ToString(*event.lifecycle_to);
    }
    log_lines_.push_back(line.str());
  }
  directsound_event_count_ = events.size();
}

void DiagnosticUiState::AppendMmeEvents() {
  if (!mme_backend_) {
    return;
  }

  const auto events = mme_backend_->diagnostic_events();
  for (std::size_t index = mme_event_count_; index < events.size(); ++index) {
    const auto& event = events[index];
    std::ostringstream line;
    line << '#' << event.sequence << ' ' << ToString(event.type) << ": "
         << event.message;
    if (event.lifecycle_to) {
      line << " -> " << ToString(*event.lifecycle_to);
    }
    log_lines_.push_back(line.str());
  }
  mme_event_count_ = events.size();
}

void DiagnosticUiState::AppendWasapiSharedEvents() {
  if (!wasapi_shared_backend_) {
    return;
  }

  const auto events = wasapi_shared_backend_->diagnostic_events();
  for (std::size_t index = wasapi_shared_event_count_; index < events.size(); ++index) {
    const auto& event = events[index];
    std::ostringstream line;
    line << '#' << event.sequence << ' ' << ToString(event.type) << ": "
         << event.message;
    if (event.lifecycle_to) {
      line << " -> " << ToString(*event.lifecycle_to);
    }
    log_lines_.push_back(line.str());
  }
  wasapi_shared_event_count_ = events.size();
}

void DiagnosticUiState::AppendWasapiExclusiveEvents() {
  if (!wasapi_exclusive_backend_) {
    return;
  }

  const auto events = wasapi_exclusive_backend_->diagnostic_events();
  for (std::size_t index = wasapi_exclusive_event_count_; index < events.size(); ++index) {
    const auto& event = events[index];
    std::ostringstream line;
    line << '#' << event.sequence << ' ' << ToString(event.type) << ": "
         << event.message;
    if (event.lifecycle_to) {
      line << " -> " << ToString(*event.lifecycle_to);
    }
    log_lines_.push_back(line.str());
  }
  wasapi_exclusive_event_count_ = events.size();
}

void DiagnosticUiState::UpdatePlaybackCompletionStatus(
    BackendApi backend,
    DeviceLifecycleState state,
    const RealtimeStats& stats) {
  const auto completion_status = PlaybackCompletionStatusText(backend, state);
  if (!completion_status) {
    return;
  }

  status_text_ = *completion_status;
  last_run_ok_ = true;

  if (last_playback_completion_status_ == *completion_status) {
    return;
  }

  std::ostringstream line;
  line << *completion_status
       << "; signal_frames_generated=" << stats.frames_generated;
  const auto keep_alive_frames =
      KeepAliveOrSilenceFramesSubmitted(stats);
  if (keep_alive_frames > 0) {
    line << " keep_alive_or_silence_frames_submitted="
         << keep_alive_frames;
  }
  log_lines_.push_back(line.str());
  last_playback_completion_status_ = *completion_status;
}

void DiagnosticUiState::UpdatePcmSummaryFromEvents(
    BackendApi backend,
    const std::vector<DiagnosticEvent>& events,
    const RealtimeStats& stats) {
  if (events.empty()) {
    return;
  }
  last_pcm_summary_ = BuildPcmRunSummary(
      backend,
      events.front().device_id,
      events,
      stats);
}

void DiagnosticUiState::RecordReleaseResult(BackendApi backend,
                                            const OperationResult& result) {
  last_release_attempted_ = true;
  last_release_ok_ = result.ok;
  last_release_backend_ = ToString(backend);
  last_release_status_ = status_text_;
  last_release_error_ = result.ok ? "" : result.error.message;
  last_release_stats_ = stats_;
}

void DiagnosticUiState::UpdateLastBackendError(const BackendError& error,
                                               const char* backend_label) {
  if (error.code == 0 && error.message.empty()) {
    if (last_run_ok_) {
      last_backend_error_summary_ = "none";
    }
    return;
  }

  std::ostringstream summary;
  summary << backend_label << " error";
  if (error.code != 0) {
    summary << " code=" << error.code;
  }
  if (!error.message.empty()) {
    summary << ": " << error.message;
  }
  const auto next_summary = summary.str();
  if (last_backend_error_summary_ != next_summary) {
    log_lines_.push_back("runtime backend error: " + next_summary);
  }
  last_backend_error_summary_ = next_summary;
  last_run_ok_ = false;
  status_text_ = next_summary;
}

}  // namespace aptt
