#include <cstdint>
#include <cstdlib>
#include <filesystem>
#include <iostream>
#include <optional>
#include <string_view>
#include <utility>
#include <vector>

#include "app/command_line_args.h"
#include "app/diagnostic_ui_state.h"
#include "backends/kernel_streaming_discovery.h"
#include "core/dop_generator.h"
#include "core/native_dsd_generator.h"

#ifndef APTT_ENABLE_ASIO
#define APTT_ENABLE_ASIO 0
#endif

namespace {

void Expect(bool condition, std::string_view message) {
  if (!condition) {
    std::cerr << "FAILED: " << message << "\n";
    std::exit(1);
  }
}

void ExpectEquals(std::string_view actual,
                  std::string_view expected,
                  std::string_view message) {
  if (actual != expected) {
    std::cerr << "FAILED: " << message << " expected=\"" << expected
              << "\" actual=\"" << actual << "\"\n";
    std::exit(1);
  }
}

bool ContainsLine(const std::vector<std::string>& lines, std::string_view needle) {
  for (const auto& line : lines) {
    if (line.find(needle) != std::string::npos) {
      return true;
    }
  }
  return false;
}

bool SameFormatForTest(const aptt::FormatDescriptor& left,
                       const aptt::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 ContainsFormatForTest(const std::vector<aptt::FormatDescriptor>& formats,
                           const aptt::FormatDescriptor& target) {
  for (const auto& format : formats) {
    if (SameFormatForTest(format, target)) {
      return true;
    }
  }
  return false;
}

aptt::FormatDescriptor MakeTestPcmFormat(std::uint32_t sample_rate_hz,
                                         aptt::SampleType sample_type,
                                         std::uint32_t valid_bits,
                                         std::uint32_t container_bits,
                                         std::uint32_t channels) {
  aptt::FormatDescriptor format;
  format.signal_mode = aptt::SignalMode::kPcm;
  format.sample_rate_hz = sample_rate_hz;
  format.sample_type = sample_type;
  format.valid_bits_per_sample = valid_bits;
  format.container_bits_per_sample = container_bits;
  format.channels.channel_count = channels;
  format.channels.channel_mask = channels == 1 ? 1u : 3u;
  return format;
}

std::optional<std::size_t> FindMatrixRow(
    const aptt::DeviceCapabilityMatrix& matrix,
    const aptt::FormatDescriptor& format) {
  for (std::size_t index = 0; index < matrix.rows.size(); ++index) {
    const auto& row = matrix.rows[index];
    if (row.signal_mode == format.signal_mode &&
        row.sample_type == format.sample_type &&
        row.valid_bits_per_sample == format.valid_bits_per_sample &&
        row.container_bits_per_sample == format.container_bits_per_sample &&
        row.channels.channel_count == format.channels.channel_count &&
        row.channels.channel_mask == format.channels.channel_mask) {
      return index;
    }
  }
  return std::nullopt;
}

std::optional<std::size_t> FindMatrixColumn(
    const aptt::DeviceCapabilityMatrix& matrix,
    std::uint32_t sample_rate_hz) {
  for (std::size_t index = 0; index < matrix.sample_rate_columns.size();
       ++index) {
    if (matrix.sample_rate_columns[index] == sample_rate_hz) {
      return index;
    }
  }
  return std::nullopt;
}

const aptt::CapabilityCell& MatrixCell(
    const aptt::DeviceCapabilityMatrix& matrix,
    std::size_t row,
    std::size_t column) {
  return matrix.cells[row * matrix.sample_rate_columns.size() + column];
}

void SelectMatrixCellForBackend(aptt::DiagnosticUiState& state,
                                aptt::BackendApi backend,
                                const aptt::FormatDescriptor& format) {
  state.BuildDeviceCapabilityMatrix();
  Expect(state.device_capability_matrix().has_value(),
         "matrix exists before selecting backend cell");
  const auto& matrix = *state.device_capability_matrix();
  Expect(matrix.target_backend == backend, "matrix target backend matches");
  const auto row = FindMatrixRow(matrix, format);
  const auto column = FindMatrixColumn(matrix, format.sample_rate_hz);
  Expect(row.has_value(), "requested matrix row exists");
  Expect(column.has_value(), "requested matrix column exists");
  Expect(MatrixCell(matrix, *row, *column).selectable,
         "requested matrix cell is selectable");
  Expect(state.SelectCapabilityMatrixCell(*row, *column),
         "requested matrix cell selection succeeds");
}

aptt::DiscoverySnapshot MakeAsioPcmSnapshot(
    bool known_problem,
    std::uint32_t sample_rate_hz = 48000) {
  aptt::DiscoverySnapshot snapshot;
  snapshot.backend = aptt::BackendApi::kAsio;

  aptt::DeviceInfo device;
  device.backend = aptt::BackendApi::kAsio;
  device.display_name = "Fixture ASIO Driver";
  device.driver_name = "Fixture ASIO Driver";
  device.stable_id = "asio:{01234567-89AB-CDEF-0123-456789ABCDEF}";
  device.is_known_problem_device = known_problem;

  auto device_snapshot = aptt::MakeDiscoveredDeviceSnapshot(
      device,
      aptt::DeviceAvailability::kActive);
  aptt::CapabilityProbeRecord supported;
  supported.kind = aptt::CapabilityProbeKind::kFormatSupport;
  supported.support = aptt::CapabilitySupport::kSupported;
  supported.accepted_format = aptt::FormatDescriptor{};
  supported.accepted_format->signal_mode = aptt::SignalMode::kPcm;
  supported.accepted_format->sample_rate_hz = sample_rate_hz;
  supported.accepted_format->sample_type = aptt::SampleType::kFloat32;
  supported.accepted_format->valid_bits_per_sample = 32;
  supported.accepted_format->container_bits_per_sample = 32;
  supported.accepted_format->channels.channel_count = 2;
  supported.accepted_format->channels.channel_mask = 3;
  supported.requested_format = supported.accepted_format;
  device_snapshot.probes.push_back(supported);
  snapshot.devices.push_back(device_snapshot);
  return snapshot;
}

aptt::DiscoverySnapshot MakeTwoDeviceAsioPcmSnapshot(
    std::uint32_t sample_rate_hz = 48000) {
  auto snapshot = MakeAsioPcmSnapshot(false, sample_rate_hz);
  aptt::DeviceInfo second_device;
  second_device.backend = aptt::BackendApi::kAsio;
  second_device.display_name = "Second Fixture ASIO Driver";
  second_device.driver_name = "Second Fixture ASIO Driver";
  second_device.stable_id = "asio:{22222222-3333-4444-5555-666666666666}";

  auto second_snapshot = aptt::MakeDiscoveredDeviceSnapshot(
      second_device,
      aptt::DeviceAvailability::kActive);
  aptt::CapabilityProbeRecord supported;
  supported.kind = aptt::CapabilityProbeKind::kFormatSupport;
  supported.support = aptt::CapabilitySupport::kSupported;
  supported.accepted_format = aptt::FormatDescriptor{};
  supported.accepted_format->signal_mode = aptt::SignalMode::kPcm;
  supported.accepted_format->sample_rate_hz = sample_rate_hz;
  supported.accepted_format->sample_type = aptt::SampleType::kFloat32;
  supported.accepted_format->valid_bits_per_sample = 32;
  supported.accepted_format->container_bits_per_sample = 32;
  supported.accepted_format->channels.channel_count = 2;
  supported.accepted_format->channels.channel_mask = 3;
  supported.requested_format = supported.accepted_format;
  second_snapshot.probes.push_back(supported);
  snapshot.devices.push_back(second_snapshot);
  return snapshot;
}

aptt::DiscoverySnapshot MakeWasapiPcmSnapshot(
    aptt::BackendApi backend,
    std::string stable_id = "wasapi:{fixture-endpoint}",
    bool known_problem = false) {
  aptt::DiscoverySnapshot snapshot;
  snapshot.backend = backend;

  aptt::DeviceInfo device;
  device.backend = backend;
  device.display_name = "Fixture WASAPI endpoint";
  device.stable_id = std::move(stable_id);
  device.driver_name = "WASAPI/Core Audio";
  device.is_known_problem_device = known_problem;

  auto device_snapshot = aptt::MakeDiscoveredDeviceSnapshot(
      device,
      aptt::DeviceAvailability::kActive);
  aptt::CapabilityProbeRecord supported;
  supported.kind = aptt::CapabilityProbeKind::kFormatSupport;
  supported.support = aptt::CapabilitySupport::kSupported;
  supported.accepted_format = aptt::WasapiDefaultPcmCandidate();
  supported.requested_format = supported.accepted_format;
  supported.backend_fields["api"] = "IAudioClient::IsFormatSupported";
  device_snapshot.probes.push_back(supported);
  snapshot.devices.push_back(device_snapshot);
  return snapshot;
}

aptt::DiscoverySnapshot MakeWasapiClosestMatchSnapshot() {
  aptt::DiscoverySnapshot snapshot;
  snapshot.backend = aptt::BackendApi::kWasapiShared;

  aptt::DeviceInfo device;
  device.backend = aptt::BackendApi::kWasapiShared;
  device.display_name = "Fixture WASAPI endpoint";
  device.stable_id = "wasapi:{fixture-endpoint}";
  device.driver_name = "WASAPI/Core Audio";

  auto device_snapshot = aptt::MakeDiscoveredDeviceSnapshot(
      device,
      aptt::DeviceAvailability::kActive);
  aptt::CapabilityProbeRecord closest;
  closest.kind = aptt::CapabilityProbeKind::kFormatSupport;
  closest.support = aptt::CapabilitySupport::kClosestMatch;
  closest.requested_format =
      MakeTestPcmFormat(44100, aptt::SampleType::kInt16, 16, 16, 2);
  closest.accepted_format = aptt::WasapiDefaultPcmCandidate();
  closest.backend_fields["api"] = "IAudioClient::IsFormatSupported";
  closest.detail = "closest format returned by driver";
  device_snapshot.probes.push_back(closest);
  snapshot.devices.push_back(device_snapshot);
  return snapshot;
}

aptt::DiscoverySnapshot MakeMmeDeviceSnapshot() {
  aptt::DiscoverySnapshot snapshot;
  snapshot.backend = aptt::BackendApi::kMme;

  aptt::DeviceInfo device;
  device.backend = aptt::BackendApi::kMme;
  device.display_name = "Fixture waveOut";
  device.stable_id = "mme:waveout:1";
  device.driver_name = "MME/waveOut";

  snapshot.devices.push_back(aptt::MakeDiscoveredDeviceSnapshot(
      device,
      aptt::DeviceAvailability::kActive));
  return snapshot;
}

aptt::DiscoverySnapshot MakeDirectSoundDeviceSnapshot() {
  aptt::DiscoverySnapshot snapshot;
  snapshot.backend = aptt::BackendApi::kDirectSound;
  snapshot.devices.push_back(aptt::MakeDirectSoundDeviceSnapshot(
      aptt::DirectSoundGuidStableIdFromText(
          "{01234567-89AB-CDEF-0123-456789ABCDEF}"),
      "Fixture DirectSound",
      "fixture.dll",
      false));
  return snapshot;
}

aptt::DiscoverySnapshot MakeAsioDeviceSnapshot() {
  aptt::DiscoverySnapshot snapshot;
  snapshot.backend = aptt::BackendApi::kAsio;

  aptt::DeviceInfo device;
  device.backend = aptt::BackendApi::kAsio;
  device.display_name = "Fixture ASIO Driver";
  device.driver_name = "Fixture ASIO Driver";
  device.stable_id = "asio:{01234567-89AB-CDEF-0123-456789ABCDEF}";

  snapshot.devices.push_back(aptt::MakeDiscoveredDeviceSnapshot(
      device,
      aptt::DeviceAvailability::kActive));
  return snapshot;
}

aptt::DiscoverySnapshot MakeKernelStreamingProbeSnapshot() {
  aptt::DiscoverySnapshot snapshot;
  snapshot.backend = aptt::BackendApi::kKernelStreaming;
  snapshot.opens_audio_device = true;
  snapshot.initializes_stream = false;
  snapshot.starts_stream = false;

  auto device_snapshot = aptt::MakeKernelStreamingPinSnapshot(
      R"(\\?\SWD#MMDEVAPI#{fixture-filter})",
      3,
      "render",
      "sink",
      1,
      aptt::DeviceAvailability::kActive);
  device_snapshot.device.display_name = "Fixture Kernel Streaming pin";
  device_snapshot.backend_fields["ks_filter_symbolic_link"] =
      R"(\\?\SWD#MMDEVAPI#{fixture-filter})";
  device_snapshot.backend_fields["ks_pin_id"] = "3";
  device_snapshot.backend_fields["ks_pin_dataflow"] = "render";
  device_snapshot.backend_fields["ks_pin_communication"] = "sink";
  device_snapshot.backend_fields["ks_data_range_count"] = "1";
  device_snapshot.backend_fields["ks_data_format_specifier"] =
      "KSDATAFORMAT_SPECIFIER_WAVEFORMATEX";
  device_snapshot.backend_fields["opens_filter"] = "true";
  device_snapshot.backend_fields["creates_pin"] = "false";
  device_snapshot.backend_fields["starts_stream"] = "false";

  aptt::CapabilityProbeRecord accepted;
  accepted.kind = aptt::CapabilityProbeKind::kFormatSupport;
  accepted.support = aptt::CapabilitySupport::kSupported;
  accepted.requested_format =
      MakeTestPcmFormat(48000, aptt::SampleType::kFloat32, 32, 32, 2);
  accepted.accepted_format = accepted.requested_format;
  accepted.detail =
      "Kernel Streaming fixture data range accepted exact PCM format without RUN";
  accepted.backend_fields["api"] = "Kernel Streaming pin format probe";
  accepted.backend_fields["ks_filter_symbolic_link"] =
      R"(\\?\SWD#MMDEVAPI#{fixture-filter})";
  accepted.backend_fields["ks_pin_id"] = "3";
  accepted.backend_fields["ks_pin_dataflow"] = "render";
  accepted.backend_fields["ks_pin_communication"] = "sink";
  accepted.backend_fields["ks_data_range_count"] = "1";
  accepted.backend_fields["ks_data_format_specifier"] =
      "KSDATAFORMAT_SPECIFIER_WAVEFORMATEX";
  accepted.backend_fields["opens_filter"] = "true";
  accepted.backend_fields["creates_pin"] = "false";
  accepted.backend_fields["starts_stream"] = "false";
  accepted.backend_fields["ks_result_level"] = "data_range_match";
  device_snapshot.probes.push_back(accepted);

  aptt::CapabilityProbeRecord pin_verified = accepted;
  pin_verified.requested_format =
      MakeTestPcmFormat(96000, aptt::SampleType::kFloat32, 32, 32, 2);
  pin_verified.accepted_format = pin_verified.requested_format;
  pin_verified.detail =
      "Kernel Streaming fixture exact pin creation accepted PCM format without RUN";
  pin_verified.backend_fields["creates_pin"] = "true";
  pin_verified.backend_fields["ks_result_level"] = "pin_create_verified";
  device_snapshot.probes.push_back(pin_verified);

  aptt::DopConfig dop;
  dop.dsd_rate_multiplier = 64;
  dop.channel_count = 2;
  aptt::CapabilityProbeRecord accepted_dop;
  accepted_dop.kind = aptt::CapabilityProbeKind::kFormatSupport;
  accepted_dop.support = aptt::CapabilitySupport::kSupported;
  accepted_dop.requested_format = aptt::MakeDopCarrierFormat(dop);
  accepted_dop.accepted_format = accepted_dop.requested_format;
  accepted_dop.detail =
      "Kernel Streaming fixture data range accepted exact DoP carrier without RUN";
  accepted_dop.backend_fields["api"] = "Kernel Streaming pin format probe";
  accepted_dop.backend_fields["ks_filter_symbolic_link"] =
      R"(\\?\SWD#MMDEVAPI#{fixture-filter})";
  accepted_dop.backend_fields["ks_pin_id"] = "3";
  accepted_dop.backend_fields["ks_pin_dataflow"] = "render";
  accepted_dop.backend_fields["ks_pin_communication"] = "sink";
  accepted_dop.backend_fields["ks_data_range_count"] = "1";
  accepted_dop.backend_fields["ks_data_format_specifier"] =
      "KSDATAFORMAT_SPECIFIER_WAVEFORMATEX";
  accepted_dop.backend_fields["opens_filter"] = "true";
  accepted_dop.backend_fields["creates_pin"] = "false";
  accepted_dop.backend_fields["starts_stream"] = "false";
  accepted_dop.backend_fields["ks_result_level"] = "data_range_match";
  device_snapshot.probes.push_back(accepted_dop);

  snapshot.devices.push_back(device_snapshot);
  return snapshot;
}

aptt::DiscoverySnapshot MakeKernelStreamingNonPlaybackProbeSnapshot() {
  aptt::DiscoverySnapshot snapshot;
  snapshot.backend = aptt::BackendApi::kKernelStreaming;
  snapshot.opens_audio_device = true;
  snapshot.initializes_stream = false;
  snapshot.starts_stream = false;

  auto device_snapshot = aptt::MakeKernelStreamingPinSnapshot(
      R"(\\?\PCI#VEN_1621&DEV_0028#{fixture-lynx}\wave8)",
      1,
      "capture",
      "sink",
      1,
      aptt::DeviceAvailability::kUnavailable);
  device_snapshot.device.display_name = "Fixture Lynx capture pin";
  device_snapshot.backend_fields["ks_filter_symbolic_link"] =
      R"(\\?\PCI#VEN_1621&DEV_0028#{fixture-lynx}\wave8)";
  device_snapshot.backend_fields["ks_pin_id"] = "1";
  device_snapshot.backend_fields["ks_pin_dataflow"] = "capture";
  device_snapshot.backend_fields["ks_pin_communication"] = "sink";
  device_snapshot.backend_fields["ks_render_candidate"] = "false";
  device_snapshot.backend_fields["ks_data_range_count"] = "1";
  device_snapshot.backend_fields["ks_data_format_specifier"] =
      "KSDATAFORMAT_SPECIFIER_WAVEFORMATEX";
  device_snapshot.backend_fields["opens_filter"] = "true";
  device_snapshot.backend_fields["creates_pin"] = "false";
  device_snapshot.backend_fields["starts_stream"] = "false";

  aptt::CapabilityProbeRecord accepted;
  accepted.kind = aptt::CapabilityProbeKind::kFormatSupport;
  accepted.support = aptt::CapabilitySupport::kSupported;
  accepted.requested_format =
      MakeTestPcmFormat(96000, aptt::SampleType::kInt16, 16, 16, 2);
  accepted.accepted_format = accepted.requested_format;
  accepted.detail =
      "Kernel Streaming fixture data range matched a non-playback pin";
  accepted.backend_fields["api"] = "Kernel Streaming pin format probe";
  accepted.backend_fields["ks_filter_symbolic_link"] =
      R"(\\?\PCI#VEN_1621&DEV_0028#{fixture-lynx}\wave8)";
  accepted.backend_fields["ks_pin_id"] = "1";
  accepted.backend_fields["ks_pin_dataflow"] = "capture";
  accepted.backend_fields["ks_pin_communication"] = "sink";
  accepted.backend_fields["ks_render_candidate"] = "false";
  accepted.backend_fields["opens_filter"] = "true";
  accepted.backend_fields["creates_pin"] = "false";
  accepted.backend_fields["starts_stream"] = "false";
  accepted.backend_fields["ks_result_level"] = "data_range_match";
  device_snapshot.probes.push_back(accepted);

  snapshot.devices.push_back(device_snapshot);
  return snapshot;
}

aptt::DiscoverySnapshot MakeKernelStreamingLoopedProbeSnapshot() {
  aptt::DiscoverySnapshot snapshot;
  snapshot.backend = aptt::BackendApi::kKernelStreaming;
  snapshot.opens_audio_device = true;
  snapshot.initializes_stream = false;
  snapshot.starts_stream = false;

  auto device_snapshot = aptt::MakeKernelStreamingPinSnapshot(
      R"(\\?\PCI#VEN_1621&DEV_0028#{fixture-lynx}\wave8)",
      0,
      "render",
      "sink",
      1,
      aptt::DeviceAvailability::kActive);
  device_snapshot.device.display_name = "Fixture Lynx looped render pin";
  device_snapshot.backend_fields["ks_filter_symbolic_link"] =
      R"(\\?\PCI#VEN_1621&DEV_0028#{fixture-lynx}\wave8)";
  device_snapshot.backend_fields["ks_pin_id"] = "0";
  device_snapshot.backend_fields["ks_pin_dataflow"] = "render";
  device_snapshot.backend_fields["ks_pin_communication"] = "sink";
  device_snapshot.backend_fields["ks_render_candidate"] = "true";
  device_snapshot.backend_fields["ks_stream_write_supported"] = "false";
  device_snapshot.backend_fields["ks_standard_streaming_supported"] = "false";
  device_snapshot.backend_fields["ks_looped_streaming_supported"] = "true";
  device_snapshot.backend_fields["ks_streaming_interface_supported"] = "true";
  device_snapshot.backend_fields["ks_looped_streaming_only"] = "true";
  device_snapshot.backend_fields["ks_streaming_model"] = "standard_looped";
  device_snapshot.backend_fields["supports_standard_streaming"] = "false";
  device_snapshot.backend_fields["supports_looped_streaming"] = "true";
  device_snapshot.backend_fields["supports_wavert_rtaudio_properties"] =
      "unknown";
  device_snapshot.backend_fields["ks_playback_implementation"] =
      "unimplemented";
  device_snapshot.backend_fields["ks_pin_interface_set"] =
      "{1A8766A0-62CE-11CF-A5D6-28DB04C10000}";
  device_snapshot.backend_fields["ks_pin_interface_id"] = "1";
  device_snapshot.backend_fields["ks_transfer_mode"] = "standard_looped";
  device_snapshot.backend_fields["ks_pin_interface"] =
      "KSINTERFACE_STANDARD_LOOPED_STREAMING";
  device_snapshot.backend_fields["ks_data_range_count"] = "1";
  device_snapshot.backend_fields["ks_data_format_specifier"] =
      "KSDATAFORMAT_SPECIFIER_WAVEFORMATEX";
  device_snapshot.backend_fields["opens_filter"] = "true";
  device_snapshot.backend_fields["creates_pin"] = "false";
  device_snapshot.backend_fields["starts_stream"] = "false";

  aptt::CapabilityProbeRecord accepted;
  accepted.kind = aptt::CapabilityProbeKind::kFormatSupport;
  accepted.support = aptt::CapabilitySupport::kSupported;
  accepted.requested_format =
      MakeTestPcmFormat(96000, aptt::SampleType::kInt16, 16, 16, 2);
  accepted.accepted_format = accepted.requested_format;
  accepted.detail =
      "Kernel Streaming fixture data range matched a looped render pin";
  accepted.backend_fields["api"] = "Kernel Streaming pin format probe";
  accepted.backend_fields["ks_filter_symbolic_link"] =
      R"(\\?\PCI#VEN_1621&DEV_0028#{fixture-lynx}\wave8)";
  accepted.backend_fields["ks_pin_id"] = "0";
  accepted.backend_fields["ks_pin_dataflow"] = "render";
  accepted.backend_fields["ks_pin_communication"] = "sink";
  accepted.backend_fields["ks_render_candidate"] = "true";
  accepted.backend_fields["ks_stream_write_supported"] = "false";
  accepted.backend_fields["ks_standard_streaming_supported"] = "false";
  accepted.backend_fields["ks_looped_streaming_supported"] = "true";
  accepted.backend_fields["ks_streaming_interface_supported"] = "true";
  accepted.backend_fields["ks_looped_streaming_only"] = "true";
  accepted.backend_fields["ks_streaming_model"] = "standard_looped";
  accepted.backend_fields["supports_standard_streaming"] = "false";
  accepted.backend_fields["supports_looped_streaming"] = "true";
  accepted.backend_fields["supports_wavert_rtaudio_properties"] = "unknown";
  accepted.backend_fields["ks_playback_implementation"] = "unimplemented";
  accepted.backend_fields["ks_pin_interface_set"] =
      "{1A8766A0-62CE-11CF-A5D6-28DB04C10000}";
  accepted.backend_fields["ks_pin_interface_id"] = "1";
  accepted.backend_fields["ks_transfer_mode"] = "standard_looped";
  accepted.backend_fields["ks_pin_interface"] =
      "KSINTERFACE_STANDARD_LOOPED_STREAMING";
  accepted.backend_fields["opens_filter"] = "true";
  accepted.backend_fields["creates_pin"] = "false";
  accepted.backend_fields["starts_stream"] = "false";
  accepted.backend_fields["ks_result_level"] = "data_range_match";
  device_snapshot.probes.push_back(accepted);

  snapshot.devices.push_back(device_snapshot);
  return snapshot;
}

aptt::DiscoverySnapshot MakeKernelStreamingModelProbeSnapshot(
    std::string model,
    bool supports_standard,
    bool supports_looped,
    std::string supports_wavert,
    aptt::CapabilitySupport support = aptt::CapabilitySupport::kSupported,
    std::string accepts_wavert = "unknown") {
  aptt::DiscoverySnapshot snapshot;
  snapshot.backend = aptt::BackendApi::kKernelStreaming;
  snapshot.opens_audio_device = true;
  snapshot.initializes_stream = false;
  snapshot.starts_stream = false;

  auto device_snapshot = aptt::MakeKernelStreamingPinSnapshot(
      R"(\\?\PCI#VEN_1621&DEV_0028#{fixture-lynx}\wave8)",
      0,
      "render",
      "sink",
      1,
      aptt::DeviceAvailability::kActive);
  device_snapshot.device.display_name = "Fixture Kernel Streaming model pin";
  device_snapshot.backend_fields["ks_filter_symbolic_link"] =
      R"(\\?\PCI#VEN_1621&DEV_0028#{fixture-lynx}\wave8)";
  device_snapshot.backend_fields["ks_pin_id"] = "0";
  device_snapshot.backend_fields["ks_pin_dataflow"] = "render";
  device_snapshot.backend_fields["ks_pin_communication"] = "sink";
  device_snapshot.backend_fields["ks_render_candidate"] = "true";

  aptt::CapabilityProbeRecord record;
  record.kind = aptt::CapabilityProbeKind::kFormatSupport;
  record.support = support;
  record.requested_format =
      MakeTestPcmFormat(96000, aptt::SampleType::kInt16, 16, 16, 2);
  if (support == aptt::CapabilitySupport::kSupported) {
    record.accepted_format = record.requested_format;
  }
  record.detail = "Kernel Streaming fixture streaming-model classification";
  record.backend_fields["api"] = "Kernel Streaming pin format probe";
  record.backend_fields["ks_filter_symbolic_link"] =
      R"(\\?\PCI#VEN_1621&DEV_0028#{fixture-lynx}\wave8)";
  record.backend_fields["ks_pin_id"] = "0";
  record.backend_fields["ks_pin_dataflow"] = "render";
  record.backend_fields["ks_pin_communication"] = "sink";
  record.backend_fields["ks_render_candidate"] = "true";
  record.backend_fields["ks_streaming_model"] = model;
  record.backend_fields["supports_standard_streaming"] =
      supports_standard ? "true" : "false";
  record.backend_fields["supports_looped_streaming"] =
      supports_looped ? "true" : "false";
  record.backend_fields["supports_wavert_rtaudio_properties"] =
      std::move(supports_wavert);
  record.backend_fields["accepts_wavert_notification_buffer"] =
      std::move(accepts_wavert);
  record.backend_fields["ks_stream_write_supported"] =
      supports_standard ? "true" : "false";
  record.backend_fields["ks_standard_streaming_supported"] =
      supports_standard ? "true" : "false";
  record.backend_fields["ks_looped_streaming_supported"] =
      supports_looped ? "true" : "false";
  record.backend_fields["ks_streaming_interface_supported"] =
      (supports_standard || supports_looped) ? "true" : "false";
  record.backend_fields["ks_looped_streaming_only"] =
      supports_looped && !supports_standard ? "true" : "false";
  record.backend_fields["ks_pin_interface_set"] =
      supports_standard || supports_looped
          ? "{1A8766A0-62CE-11CF-A5D6-28DB04C10000}"
          : "unknown";
  record.backend_fields["ks_pin_interface_id"] =
      supports_standard ? "0" : (supports_looped ? "1" : "unknown");
  record.backend_fields["opens_filter"] = "true";
  record.backend_fields["creates_pin"] = "false";
  record.backend_fields["starts_stream"] = "false";
  record.backend_fields["ks_result_level"] =
      support == aptt::CapabilitySupport::kSupported ? "data_range_match"
                                                     : "unsupported";
  record.backend_fields["ks_data_range_count"] = "1";

  if (model == "standard_packet") {
    record.backend_fields["ks_playback_implementation"] = "implemented";
  } else if (model == "standard_looped") {
    record.backend_fields["ks_playback_implementation"] = "unimplemented";
  } else if (model == "wavert_cyclic") {
    record.backend_fields["ks_playback_implementation"] = "implemented";
  } else {
    record.backend_fields["ks_playback_implementation"] = "unimplemented";
  }
  record.backend_fields["ks_playback_path"] =
      record.backend_fields["ks_playback_implementation"] == "implemented"
          ? model
          : "unimplemented";

  device_snapshot.probes.push_back(record);
  device_snapshot.backend_fields = record.backend_fields;
  snapshot.devices.push_back(device_snapshot);
  return snapshot;
}

aptt::DiscoverySnapshot MakeAsioNativeDsdSnapshot() {
  aptt::DiscoverySnapshot snapshot;
  snapshot.backend = aptt::BackendApi::kAsio;

  aptt::DeviceInfo device;
  device.backend = aptt::BackendApi::kAsio;
  device.display_name = "Fixture ASIO DSD Driver";
  device.driver_name = "Fixture ASIO DSD Driver";
  device.stable_id = "asio:{89ABCDEF-0123-4567-89AB-CDEF01234567}";

  aptt::NativeDsdConfig dsd;
  dsd.dsd_rate_multiplier = 64;
  dsd.channel_count = 2;
  dsd.sample_type = aptt::SampleType::kDsd1BitLsbFirst;

  auto device_snapshot = aptt::MakeDiscoveredDeviceSnapshot(
      device,
      aptt::DeviceAvailability::kActive);
  aptt::CapabilityProbeRecord supported;
  supported.kind = aptt::CapabilityProbeKind::kFormatSupport;
  supported.support = aptt::CapabilitySupport::kSupported;
  supported.accepted_format = aptt::MakeNativeDsdFormat(dsd);
  supported.requested_format = supported.accepted_format;
  supported.backend_fields["api"] = "ASIO native DSD query";
  device_snapshot.probes.push_back(supported);
  snapshot.devices.push_back(device_snapshot);
  return snapshot;
}

void TestRunNullSessionUpdatesUiState() {
  aptt::DiagnosticUiState state;
  state.RunNullSession();

  Expect(state.last_run_ok(), "Null session succeeds");
  ExpectEquals(state.status_text(), "ready", "status becomes ready");
  Expect(state.stats().frames_generated == 4800, "UI state stores frame count");
  Expect(!state.log_lines().empty(), "UI state stores log lines");
  Expect(!state.bundle_path().has_value(), "bundle path absent when not requested");
  Expect(state.last_pcm_summary().has_value(),
         "UI state stores comparable PCM summary");
  Expect(state.last_pcm_summary()->backend == aptt::BackendApi::kNull,
         "Null run summary records backend");
  Expect(!state.last_pcm_summary()->auto_backend_switch_attempted,
         "PCM summary does not imply backend auto-switch");
}

void TestRunNullSessionCanWriteBundle() {
  const auto out = std::filesystem::current_path() / "ui_state_bundle_output";
  std::filesystem::remove_all(out);

  aptt::DiagnosticUiState state;
  state.RunNullSession(out);

  Expect(state.last_run_ok(), "Null session with bundle succeeds");
  Expect(state.bundle_path() == out, "UI state stores bundle path");
  Expect(std::filesystem::exists(out / "summary.txt"), "bundle summary exists");
}

void TestUiCanExportCurrentDiagnosticBundle() {
  const auto out = std::filesystem::current_path() / "ui_state_export_output";
  std::filesystem::remove_all(out);

  aptt::DiagnosticUiState state;
  auto settings = state.settings();
  settings.log_directory = out;
  state.UpdateSettings(settings);

  state.RunNullSession();
  Expect(state.has_exportable_diagnostic(),
         "Null session is exportable after it runs");
  state.ExportDiagnosticBundle();

  Expect(state.last_run_ok(), "current diagnostic export succeeds");
  Expect(state.bundle_path().has_value(), "export reports bundle path");
  Expect(state.bundle_path()->extension() == ".zip",
         "export reports zip bundle path");
  Expect(std::filesystem::exists(*state.bundle_path()), "zip bundle exists");

  auto directory = *state.bundle_path();
  directory.replace_extension();
  Expect(std::filesystem::exists(directory / "bundle_manifest.json"),
         "directory bundle manifest exists");
  Expect(std::filesystem::exists(directory / "build_metadata.json"),
         "directory build metadata exists");
  Expect(std::filesystem::exists(directory / "device_snapshot.json"),
         "directory device snapshot exists");
  Expect(std::filesystem::exists(directory / "summary.csv"),
         "directory summary CSV exists");
}

void TestCanLoadAndSelectDiscoverySnapshotWithoutRealApi() {
  aptt::DiscoverySnapshot snapshot;
  snapshot.backend = aptt::BackendApi::kWasapiShared;

  aptt::DeviceInfo device;
  device.backend = aptt::BackendApi::kWasapiShared;
  device.display_name = "Fixture USB DAC";
  device.stable_id = "wasapi:{fixture-endpoint}";
  device.driver_name = "WASAPI/Core Audio";
  device.is_known_problem_device = true;

  snapshot.devices.push_back(aptt::MakeDiscoveredDeviceSnapshot(
      device,
      aptt::DeviceAvailability::kActive));

  aptt::DiagnosticUiState state;
  state.LoadDiscoverySnapshot(snapshot);

  Expect(state.last_run_ok(), "dry-run discovery snapshot is accepted");
  Expect(std::string_view(state.status_text()) == "devices loaded",
         "discovery load updates status");
  Expect(state.discovery_snapshot().devices.size() == 1,
         "UI state stores discovery snapshot");
  Expect(!state.selected_device().has_value(),
         "no device is selected before explicit selection");
  Expect(!state.last_pcm_summary().has_value(),
         "loading discovery resets previous PCM summary");
  Expect(state.SelectDiscoveredDeviceById("wasapi:{fixture-endpoint}"),
         "stable ID selection succeeds");
  Expect(state.selected_device().has_value(), "selected device is stored");
  Expect(!state.selected_playback_format().has_value(),
         "no accepted playback format is selected from discovery-only data");
  Expect(state.selected_device()->is_known_problem_device,
         "known-problem flag survives selection");
  Expect(!state.SelectDiscoveredDeviceById("missing-device"),
         "missing stable ID selection fails");
}

void TestDeviceFirstMatrixBuildDoesNotRequirePlaybackRoute() {
  aptt::DiagnosticUiState state;
  state.LoadDiscoverySnapshot(MakeWasapiPcmSnapshot(
      aptt::BackendApi::kWasapiShared));
  Expect(state.SelectDiscoveredDeviceById("wasapi:{fixture-endpoint}"),
         "target device selection succeeds");
  Expect(!state.selected_playback_format().has_value(),
         "plain discovery does not select a playback format");

  state.BuildDeviceCapabilityMatrix();

  Expect(state.device_capability_matrix().has_value(),
         "selected target device can produce a capability matrix");
  const auto& matrix = *state.device_capability_matrix();
  Expect(!matrix.rows.empty(),
         "standard matrix contains at least one checked output format");
  Expect(matrix.target_backend == aptt::BackendApi::kWasapiShared,
         "matrix is scoped to the requested API");
  Expect(!matrix.sample_rate_columns.empty(),
         "matrix columns are sample rates");
  const auto row = FindMatrixRow(matrix, aptt::WasapiDefaultPcmCandidate());
  const auto sample_rate_column =
      FindMatrixColumn(matrix, aptt::WasapiDefaultPcmCandidate().sample_rate_hz);
  Expect(row.has_value() && sample_rate_column.has_value(),
         "expected WASAPI shared matrix coordinates exist");
  Expect(MatrixCell(matrix, *row, *sample_rate_column).result_status !=
             aptt::CapabilityCellStatus::kUnchecked,
         "target API cell is checked from fresh evidence");
  Expect(!state.selected_test_condition().has_value(),
         "matrix build alone does not select a test condition");
}

void TestMatrixRowsPreserveCandidatesAndMarkUnsupportedCells() {
  aptt::DiagnosticUiState state;
  state.LoadProbeSnapshotForCurrentFormat(MakeWasapiClosestMatchSnapshot());
  Expect(state.SelectDiscoveredDeviceById("wasapi:{fixture-endpoint}"),
         "closest-match WASAPI device selection succeeds");

  state.BuildDeviceCapabilityMatrix();

  Expect(state.device_capability_matrix().has_value(),
         "capability matrix exists for closest-match evidence");
  const auto& matrix = *state.device_capability_matrix();
  const auto accepted_row =
      FindMatrixRow(matrix, aptt::WasapiDefaultPcmCandidate());
  const auto rejected_requested_row = FindMatrixRow(
      matrix,
      MakeTestPcmFormat(44100, aptt::SampleType::kInt16, 16, 16, 2));
  const auto shared_column =
      FindMatrixColumn(matrix, aptt::WasapiDefaultPcmCandidate().sample_rate_hz);
  const auto rejected_column = FindMatrixColumn(matrix, 44100);
  Expect(accepted_row.has_value(),
         "matrix row is the accepted playable format");
  Expect(rejected_requested_row.has_value(),
         "matrix keeps the rejected requested format as a candidate row");
  Expect(shared_column.has_value(), "WASAPI shared matrix column exists");
  Expect(rejected_column.has_value(), "rejected request sample-rate column exists");
  const auto& cell = MatrixCell(matrix, *accepted_row, *shared_column);
  Expect(cell.result_status == aptt::CapabilityCellStatus::kAvailable,
         "closest-match accepted format is shown as available");
  Expect(cell.selectable,
         "closest-match accepted format is selectable from playable rows");
  Expect(state.SelectCapabilityMatrixCell(*accepted_row, *shared_column),
         "accepted playable row can create the test condition");
  Expect(state.selected_test_condition().has_value(),
         "test condition is created from accepted playable format");
  Expect(SameFormatForTest(
             state.selected_test_condition()->accepted_playback_format,
             aptt::WasapiDefaultPcmCandidate()),
         "test condition stores the playable accepted format");

  const auto& rejected_cell =
      MatrixCell(matrix, *rejected_requested_row, *rejected_column);
  Expect(rejected_cell.result_status ==
             aptt::CapabilityCellStatus::kUnsupported,
         "closest-match requested format is shown as unsupported");
  Expect(!rejected_cell.selectable,
         "unsupported requested format is not selectable");
}

void TestCapabilityScanChecksSelectedDeviceWithoutPriorProbeRows() {
  aptt::DiscoverySnapshot snapshot;
  snapshot.backend = aptt::BackendApi::kWasapiShared;

  aptt::DeviceInfo device;
  device.backend = aptt::BackendApi::kWasapiShared;
  device.display_name = "Fixture WASAPI endpoint without probe rows";
  device.stable_id = "wasapi:{fixture-endpoint-without-probes}";
  device.driver_name = "WASAPI/Core Audio";
  snapshot.devices.push_back(aptt::MakeDiscoveredDeviceSnapshot(
      device,
      aptt::DeviceAvailability::kActive));

  aptt::DiagnosticUiState state;
  state.LoadDiscoverySnapshot(snapshot);
  Expect(state.SelectDiscoveredDeviceById(
             "wasapi:{fixture-endpoint-without-probes}"),
         "plain target device selection succeeds");

  state.BuildDeviceCapabilityMatrix();

  Expect(state.device_capability_matrix().has_value(),
         "capability scan builds a matrix from a plain device row");
  const auto& matrix = *state.device_capability_matrix();
  const auto row = FindMatrixRow(matrix, aptt::WasapiDefaultPcmCandidate());
  const auto shared_column =
      FindMatrixColumn(matrix, aptt::WasapiDefaultPcmCandidate().sample_rate_hz);
  Expect(matrix.target_backend == aptt::BackendApi::kWasapiShared,
         "matrix is scoped to the selected WASAPI shared API");
  Expect(row.has_value() && shared_column.has_value(),
         "expected matrix coordinates exist");

  Expect(MatrixCell(matrix, *row, *shared_column).result_status !=
             aptt::CapabilityCellStatus::kUnchecked,
         "shared WASAPI cell is checked by the scan");
  Expect(!state.selected_test_condition().has_value(),
         "scan does not select a test condition automatically");
}

void TestSelectingUsableMatrixCellCreatesTestCondition() {
  aptt::DiagnosticUiState state;
  state.LoadProbeSnapshotForCurrentFormat(MakeWasapiPcmSnapshot(
      aptt::BackendApi::kWasapiShared));
  Expect(state.SelectDiscoveredDeviceById("wasapi:{fixture-endpoint}"),
         "fresh WASAPI probe device selection succeeds");
  state.BuildDeviceCapabilityMatrix();

  const auto& matrix = *state.device_capability_matrix();
  const auto row = FindMatrixRow(matrix, aptt::WasapiDefaultPcmCandidate());
  const auto column =
      FindMatrixColumn(matrix, aptt::WasapiDefaultPcmCandidate().sample_rate_hz);
  Expect(row.has_value(), "WASAPI default PCM row is present");
  Expect(column.has_value(), "WASAPI shared column is present");
  const auto& cell = MatrixCell(matrix, *row, *column);
  Expect(cell.selectable, "fresh supported matrix cell is selectable");

  Expect(state.SelectCapabilityMatrixCell(*row, *column),
         "usable matrix cell can be selected");
  Expect(state.selected_test_condition().has_value(),
         "matrix selection creates SelectedTestCondition");
  Expect(state.selected_test_condition()->backend ==
             aptt::BackendApi::kWasapiShared,
         "test condition stores backend");
  Expect(state.selected_playback_backend() ==
             aptt::BackendApi::kWasapiShared,
         "matrix selection stores playback backend");
  Expect(state.selected_playback_format().has_value(),
         "matrix selection stores accepted format");
  Expect(!state.selected_test_condition_is_stale(),
         "fresh matrix condition is not stale");
}

void TestStartRequiresSelectedMatrixCondition() {
  aptt::DiagnosticUiState state;
  state.LoadProbeSnapshotForCurrentFormat(MakeWasapiPcmSnapshot(
      aptt::BackendApi::kWasapiShared));
  Expect(state.SelectDiscoveredDeviceById("wasapi:{fixture-endpoint}"),
         "device selection succeeds before start gate test");
  state.BuildDeviceCapabilityMatrix();

  state.StartWasapiSharedPcm();

  Expect(!state.last_run_ok(),
         "start is blocked before a matrix cell/test condition is selected");
  Expect(!state.has_active_wasapi_shared_backend(),
         "blocked start does not open WASAPI shared backend");
}

void TestTargetDeviceChangeInvalidatesMatrixAndCondition() {
  aptt::DiagnosticUiState state;
  auto settings = state.settings();
  settings.requested_backend = aptt::BackendApi::kAsio;
  state.UpdateSettings(settings);
  state.LoadProbeSnapshotForCurrentFormat(MakeTwoDeviceAsioPcmSnapshot());
  Expect(state.SelectDiscoveredDeviceById(
             "asio:{01234567-89AB-CDEF-0123-456789ABCDEF}"),
         "first ASIO device selection succeeds");
  state.BuildDeviceCapabilityMatrix();
  const auto& matrix = *state.device_capability_matrix();
  const auto row = FindMatrixRow(matrix, aptt::WasapiDefaultPcmCandidate());
  const auto column =
      FindMatrixColumn(matrix, aptt::WasapiDefaultPcmCandidate().sample_rate_hz);
  Expect(row.has_value(), "ASIO PCM row exists before target change");
  Expect(column.has_value(), "ASIO column exists before target change");
  if (MatrixCell(matrix, *row, *column).selectable) {
    Expect(state.SelectCapabilityMatrixCell(*row, *column),
           "first device matrix cell can be selected");
  }

  Expect(state.SelectDiscoveredDeviceById(
             "asio:{22222222-3333-4444-5555-666666666666}"),
         "second target device selection succeeds");

  Expect(!state.device_capability_matrix().has_value(),
         "changing target device clears the old matrix");
  Expect(!state.selected_test_condition().has_value(),
         "changing target device clears the selected test condition");
}

void TestSignalSettingsDoNotInvalidateMatrix() {
  aptt::DiagnosticUiState state;
  state.LoadDiscoverySnapshot(MakeWasapiPcmSnapshot(
      aptt::BackendApi::kWasapiShared));
  Expect(state.SelectDiscoveredDeviceById("wasapi:{fixture-endpoint}"),
         "device selection succeeds before signal-setting test");
  state.BuildDeviceCapabilityMatrix();
  const auto scan_revision =
      state.device_capability_matrix()->scan_revision;

  auto settings = state.settings();
  settings.amplitude_dbfs = -24.0;
  settings.duration_ms = 3000;
  state.UpdateSettings(settings);

  Expect(state.device_capability_matrix().has_value(),
         "matrix remains present after signal setting change");
  Expect(!state.device_capability_matrix()->stale,
         "amplitude/duration do not stale the matrix");
  Expect(state.device_capability_matrix()->scan_revision == scan_revision,
         "amplitude/duration do not rebuild the matrix");
}

void TestDopAndNativeDsdMatrixGuards() {
  aptt::DiagnosticUiState state;
  state.LoadProbeSnapshotForCurrentFormat(MakeWasapiPcmSnapshot(
      aptt::BackendApi::kWasapiShared));
  Expect(state.SelectDiscoveredDeviceById("wasapi:{fixture-endpoint}"),
         "WASAPI shared target selection succeeds");
  state.BuildDeviceCapabilityMatrix();

  const auto& matrix = *state.device_capability_matrix();
  const auto dop_row = FindMatrixRow(matrix, aptt::MakeDopCarrierFormat(
      aptt::DopConfig{}));
  const auto native_row = FindMatrixRow(matrix, aptt::MakeNativeDsdFormat(
      aptt::NativeDsdConfig{}));
  const auto dop_col = FindMatrixColumn(matrix, aptt::DopCarrierSampleRateHz(64));
  const auto native_col = FindMatrixColumn(matrix, aptt::NativeDsdRateHz(64));
  Expect(dop_col.has_value() && native_col.has_value(),
         "required sample-rate columns exist");
  Expect(dop_row.has_value(),
         "unsupported DoP remains visible as a candidate matrix row");
  Expect(native_row.has_value(),
         "unsupported native DSD remains visible as a candidate matrix row");
  Expect(MatrixCell(matrix, *dop_row, *dop_col).result_status ==
             aptt::CapabilityCellStatus::kNotApplicable,
         "WASAPI shared DoP cell is marked not applicable");
  Expect(MatrixCell(matrix, *native_row, *native_col).result_status ==
             aptt::CapabilityCellStatus::kNotApplicable,
         "WASAPI shared native DSD cell is marked not applicable");
}

void TestMatrixRowsCoverWidePcmAndDsdRangesByDefault() {
  aptt::DiagnosticUiState state;
  auto settings = state.settings();
  settings.requested_backend = aptt::BackendApi::kAsio;
  state.UpdateSettings(settings);
  state.LoadDiscoverySnapshot(MakeAsioDeviceSnapshot());
  Expect(state.SelectDiscoveredDeviceById(
             "asio:{01234567-89AB-CDEF-0123-456789ABCDEF}"),
         "ASIO target device selection succeeds for wide scan rows");

  state.BuildDeviceCapabilityMatrix();
  const auto& matrix = *state.device_capability_matrix();
  Expect(matrix.rows.size() >= 9,
         "default matrix includes PCM, DoP, and native DSD format rows");
  Expect(FindMatrixColumn(matrix, 786000).has_value(),
         "default matrix includes the requested 786 kHz column");
  Expect(FindMatrixRow(matrix,
                       MakeTestPcmFormat(786000,
                                         aptt::SampleType::kInt24Packed,
                                         24,
                                         24,
                                         2)).has_value(),
         "default matrix includes the requested 786 kHz packed 24-bit PCM row");
  Expect(FindMatrixColumn(matrix, 1411200).has_value(),
         "default matrix includes 1411.2 kHz column");
  Expect(FindMatrixRow(matrix,
                       MakeTestPcmFormat(1411200,
                                         aptt::SampleType::kFloat32,
                                         32,
                                         32,
                                         2)).has_value(),
         "default matrix includes 1411.2 kHz float32 PCM");
  Expect(FindMatrixColumn(matrix, 1536000).has_value(),
         "default matrix includes 1536 kHz column");
  Expect(FindMatrixRow(matrix,
                       MakeTestPcmFormat(1536000,
                                         aptt::SampleType::kInt32,
                                         32,
                                         32,
                                         2)).has_value(),
         "default matrix includes 1536 kHz int32 PCM");
  Expect(FindMatrixRow(matrix,
                       MakeTestPcmFormat(786000,
                                         aptt::SampleType::kInt24In32,
                                         24,
                                         32,
                                         2)).has_value(),
         "default matrix includes the requested 786 kHz 24-bit PCM row");

  aptt::DopConfig dop;
  dop.dsd_rate_multiplier = 2048;
  dop.channel_count = 2;
  Expect(FindMatrixRow(matrix, aptt::MakeDopCarrierFormat(dop)).has_value(),
         "default matrix includes DoP DSD2048 carrier");
  Expect(FindMatrixColumn(matrix, aptt::DopCarrierSampleRateHz(2048)).has_value(),
         "default matrix includes DoP DSD2048 carrier column");

  aptt::NativeDsdConfig native_dsd;
  native_dsd.dsd_rate_multiplier = 2048;
  native_dsd.channel_count = 2;
  native_dsd.sample_type = aptt::SampleType::kDsd1BitLsbFirst;
  Expect(FindMatrixRow(matrix,
                       aptt::MakeNativeDsdFormat(native_dsd)).has_value(),
         "default matrix includes native DSD2048");
  Expect(FindMatrixColumn(matrix, aptt::NativeDsdRateHz(2048)).has_value(),
         "default matrix includes native DSD2048 sample-rate column");
}

void TestReferenceMatrixCellsAreNotSelectable() {
  aptt::DiscoverySnapshot snapshot;
  snapshot.backend = aptt::BackendApi::kWasapiShared;

  aptt::DeviceInfo device;
  device.backend = aptt::BackendApi::kWasapiShared;
  device.display_name = "Fixture WASAPI endpoint";
  device.stable_id = "wasapi:{fixture-endpoint}";
  device.driver_name = "WASAPI/Core Audio";

  auto device_snapshot = aptt::MakeDiscoveredDeviceSnapshot(
      device,
      aptt::DeviceAvailability::kActive);
  aptt::CapabilityProbeRecord mix_format;
  mix_format.kind = aptt::CapabilityProbeKind::kFormatSupport;
  mix_format.support = aptt::CapabilitySupport::kSupported;
  mix_format.accepted_format = aptt::WasapiDefaultPcmCandidate();
  mix_format.backend_fields["api"] = "IAudioClient::GetMixFormat";
  device_snapshot.probes.push_back(mix_format);
  snapshot.devices.push_back(device_snapshot);

  aptt::DiagnosticUiState state;
  state.LoadProbeSnapshotForCurrentFormat(snapshot);
  Expect(state.SelectDiscoveredDeviceById("wasapi:{fixture-endpoint}"),
         "shared device selection succeeds");
  state.BuildDeviceCapabilityMatrix();
  const auto& matrix = *state.device_capability_matrix();
  const auto row = FindMatrixRow(matrix, aptt::WasapiDefaultPcmCandidate());
  const auto column =
      FindMatrixColumn(matrix, aptt::WasapiDefaultPcmCandidate().sample_rate_hz);
  Expect(row.has_value() && column.has_value(),
         "mix-format matrix cell coordinates exist");
  const auto& cell = MatrixCell(matrix, *row, *column);
  Expect(cell.result_status == aptt::CapabilityCellStatus::kReferenceInfo,
         "GetMixFormat cell is represented as reference info");
  Expect(!cell.selectable, "GetMixFormat matrix cell is not selectable");
  Expect(!state.SelectCapabilityMatrixCell(*row, *column),
         "reference matrix cell selection is rejected");
}

void TestWasapiModeSwitchCannotReuseStaleMatrixCells() {
  aptt::DiagnosticUiState state;
  state.LoadProbeSnapshotForCurrentFormat(MakeWasapiPcmSnapshot(
      aptt::BackendApi::kWasapiShared));
  Expect(state.SelectDiscoveredDeviceById("wasapi:{fixture-endpoint}"),
         "shared endpoint selection succeeds");
  state.BuildDeviceCapabilityMatrix();
  const auto& matrix = *state.device_capability_matrix();
  const auto row = FindMatrixRow(matrix, aptt::WasapiDefaultPcmCandidate());
  const auto column =
      FindMatrixColumn(matrix, aptt::WasapiDefaultPcmCandidate().sample_rate_hz);
  Expect(row.has_value() && column.has_value(),
         "shared matrix cell exists before mode switch");

  auto settings = state.settings();
  settings.requested_backend = aptt::BackendApi::kWasapiExclusive;
  state.UpdateSettings(settings);

  Expect(state.device_capability_matrix()->stale,
         "WASAPI mode switch marks the old matrix stale");
  Expect(!state.SelectCapabilityMatrixCell(*row, *column),
         "stale WASAPI matrix cell cannot be reused after mode switch");
  Expect(!state.selected_test_condition().has_value(),
         "stale matrix cell does not recreate a test condition");
}

void TestWasapiFormatProbeRequiresSelectedDevice() {
  aptt::DiagnosticUiState state;
  state.ProbeSelectedWasapiFormats();

  Expect(!state.last_run_ok(), "format probe without selection fails");
  Expect(std::string_view(state.status_text()) == "device not selected",
         "format probe reports missing selection");
  Expect(!state.log_lines().empty(), "format probe failure is logged");
}

void TestWasapiSharedStartRequiresSelectedDevice() {
  aptt::DiagnosticUiState state;
  state.StartWasapiSharedPcm();

  Expect(!state.last_run_ok(), "shared playback without selection fails");
  Expect(std::string_view(state.status_text()) == "device not selected",
         "shared playback reports missing endpoint");
  Expect(!state.has_active_wasapi_shared_backend(),
         "no WASAPI shared backend is created without endpoint");
}

void TestWasapiSharedStartRequiresAcceptedFormat() {
  aptt::DiscoverySnapshot snapshot;
  snapshot.backend = aptt::BackendApi::kWasapiShared;

  aptt::DeviceInfo device;
  device.backend = aptt::BackendApi::kWasapiShared;
  device.display_name = "Fixture WASAPI endpoint";
  device.stable_id = "wasapi:{fixture-endpoint}";
  device.driver_name = "WASAPI/Core Audio";

  snapshot.devices.push_back(aptt::MakeDiscoveredDeviceSnapshot(
      device,
      aptt::DeviceAvailability::kActive));

  aptt::DiagnosticUiState state;
  state.LoadDiscoverySnapshot(snapshot);
  Expect(state.SelectDiscoveredDeviceById("wasapi:{fixture-endpoint}"),
         "device selection succeeds");
  state.StartWasapiSharedPcm();

  Expect(!state.last_run_ok(), "shared playback without accepted format fails");
  Expect(std::string_view(state.status_text()) == "format not accepted",
         "shared playback reports missing accepted format");
  Expect(!state.has_active_wasapi_shared_backend(),
         "no WASAPI shared backend is created without accepted format");
}

void TestSelectionStoresAcceptedFormat() {
  aptt::DiscoverySnapshot snapshot;
  snapshot.backend = aptt::BackendApi::kWasapiShared;

  aptt::DeviceInfo device;
  device.backend = aptt::BackendApi::kWasapiShared;
  device.display_name = "Fixture WASAPI endpoint";
  device.stable_id = "wasapi:{fixture-endpoint}";
  device.driver_name = "WASAPI/Core Audio";

  auto device_snapshot = aptt::MakeDiscoveredDeviceSnapshot(
      device,
      aptt::DeviceAvailability::kActive);
  aptt::CapabilityProbeRecord probe;
  probe.kind = aptt::CapabilityProbeKind::kFormatSupport;
  probe.support = aptt::CapabilitySupport::kSupported;
  probe.accepted_format = aptt::WasapiDefaultPcmCandidate();
  probe.requested_format = probe.accepted_format;
  device_snapshot.probes.push_back(probe);
  snapshot.devices.push_back(device_snapshot);

  aptt::DiagnosticUiState state;
  auto settings = state.settings();
  settings.requested_backend = aptt::BackendApi::kWasapiShared;
  state.UpdateSettings(settings);
  state.LoadProbeSnapshotForCurrentFormat(snapshot);
  Expect(state.SelectDiscoveredDeviceById("wasapi:{fixture-endpoint}"),
         "device selection succeeds");
  Expect(state.selected_playback_format().has_value(),
         "accepted format is stored after selection");
  Expect(state.selected_playback_backend() == aptt::BackendApi::kWasapiShared,
         "accepted format is associated with shared mode");
}

void TestDiscoverySnapshotProbeRowsAreNotFreshWithoutProbeLoad() {
  aptt::DiagnosticUiState state;
  state.LoadDiscoverySnapshot(
      MakeWasapiPcmSnapshot(aptt::BackendApi::kWasapiShared));
  Expect(state.SelectDiscoveredDeviceById("wasapi:{fixture-endpoint}"),
         "device with old probe rows can be selected from discovery load");
  Expect(state.last_probe_rows_are_stale(),
         "plain discovery load does not mark probe rows fresh");
  Expect(!state.selected_playback_format().has_value(),
         "plain discovery load does not auto-select exact probe rows");
  Expect(!state.SelectAcceptedFormatFromProbeIndex(0),
         "plain discovery probe row cannot be accepted without real probe load");
  Expect(std::string_view(state.status_text()) == "format probe stale",
         "plain discovery probe row selection reports stale probe");
}

void TestBackendChangeClearsIncompatibleSelectedDeviceAndFormat() {
  aptt::DiagnosticUiState state;
  state.LoadProbeSnapshotForCurrentFormat(
      MakeWasapiPcmSnapshot(aptt::BackendApi::kWasapiShared));
  Expect(state.SelectDiscoveredDeviceById("wasapi:{fixture-endpoint}"),
         "WASAPI device selection succeeds before backend change");
  Expect(state.selected_device().has_value(),
         "selected device exists before backend change");
  Expect(state.selected_playback_format().has_value(),
         "accepted format exists before backend change");

  auto settings = state.settings();
  settings.requested_backend = aptt::BackendApi::kMme;
  state.UpdateSettings(settings);

  Expect(!state.selected_device().has_value(),
         "incompatible backend change clears selected device");
  Expect(!state.selected_playback_format().has_value(),
         "incompatible backend change clears accepted format");
  Expect(!state.selected_playback_backend().has_value(),
         "incompatible backend change clears accepted backend");

  state.ProbeSelectedMmeFormats();
  Expect(!state.last_run_ok(),
         "probe after incompatible backend change requires a new device");
  Expect(std::string_view(state.status_text()) == "device not selected",
         "probe after incompatible backend change reports missing device");
}

void TestWasapiBackendSwitchClearsEndpointAndAcceptedFormat() {
  aptt::DiagnosticUiState state;
  state.LoadProbeSnapshotForCurrentFormat(
      MakeWasapiPcmSnapshot(aptt::BackendApi::kWasapiShared));
  Expect(state.SelectDiscoveredDeviceById("wasapi:{fixture-endpoint}"),
         "WASAPI shared endpoint selection succeeds");
  Expect(state.selected_playback_format().has_value(),
         "accepted format exists before WASAPI mode switch");

  auto settings = state.settings();
  settings.requested_backend = aptt::BackendApi::kWasapiExclusive;
  state.UpdateSettings(settings);

  Expect(!state.selected_device().has_value(),
         "WASAPI shared/exclusive switch clears endpoint selection");
  Expect(!state.selected_playback_format().has_value(),
         "WASAPI mode switch clears accepted format");
  Expect(!state.selected_playback_backend().has_value(),
         "WASAPI mode switch clears accepted playback backend");
  Expect(!state.SelectAcceptedFormatFromProbeIndex(0),
         "old shared probe row cannot be accepted without fresh endpoint selection");
  Expect(!state.selected_playback_format().has_value(),
         "old shared probe row does not recreate an accepted format");
  Expect(!state.selected_playback_backend().has_value(),
         "old shared probe row does not recreate an accepted backend");

  state.StartWasapiExclusivePcm();
  Expect(!state.last_run_ok(),
         "WASAPI mode switch requires a fresh endpoint and accepted format before start");
  Expect(std::string_view(state.status_text()) == "device not selected",
         "start after WASAPI mode switch reports missing endpoint");
  Expect(!state.has_active_wasapi_exclusive_backend(),
         "start after WASAPI mode switch does not open a backend");
}

void TestWasapiExclusiveToSharedSwitchMarksOldProbeRowsStale() {
  aptt::DiagnosticUiState state;
  auto settings = state.settings();
  settings.requested_backend = aptt::BackendApi::kWasapiExclusive;
  state.UpdateSettings(settings);
  state.LoadProbeSnapshotForCurrentFormat(
      MakeWasapiPcmSnapshot(aptt::BackendApi::kWasapiExclusive));
  Expect(state.SelectDiscoveredDeviceById("wasapi:{fixture-endpoint}"),
         "WASAPI exclusive endpoint selection succeeds");
  Expect(state.selected_playback_format().has_value(),
         "exclusive accepted format exists before mode switch");

  settings = state.settings();
  settings.requested_backend = aptt::BackendApi::kWasapiShared;
  state.UpdateSettings(settings);

  Expect(!state.selected_device().has_value(),
         "WASAPI exclusive/shared switch clears endpoint selection");
  Expect(!state.selected_playback_format().has_value(),
         "WASAPI shared switch clears accepted format");
  Expect(!state.SelectAcceptedFormatFromProbeIndex(0),
         "old exclusive probe row cannot be accepted without fresh endpoint selection");

  state.StartWasapiSharedPcm();
  Expect(!state.last_run_ok(),
         "WASAPI shared start remains blocked after old exclusive row");
  Expect(!state.has_active_wasapi_shared_backend(),
         "old exclusive row does not open a WASAPI shared backend");
}

void TestWasapiModeSwitchFreshProbeRowsCanBeAccepted() {
  aptt::DiagnosticUiState state;
  state.LoadProbeSnapshotForCurrentFormat(
      MakeWasapiPcmSnapshot(aptt::BackendApi::kWasapiShared));
  Expect(state.SelectDiscoveredDeviceById("wasapi:{fixture-endpoint}"),
         "WASAPI shared endpoint selection succeeds before fresh reprobe test");

  auto settings = state.settings();
  settings.requested_backend = aptt::BackendApi::kWasapiExclusive;
  state.UpdateSettings(settings);
  Expect(!state.selected_device().has_value(),
         "old shared endpoint is cleared immediately after exclusive switch");

  state.LoadProbeSnapshotForCurrentFormat(
      MakeWasapiPcmSnapshot(aptt::BackendApi::kWasapiExclusive));
  Expect(state.SelectDiscoveredDeviceById("wasapi:{fixture-endpoint}"),
         "fresh exclusive endpoint probe selection succeeds");
  Expect(!state.last_probe_rows_are_stale(),
         "fresh exclusive probe rows are not stale");
  Expect(state.selected_playback_format().has_value(),
         "fresh exclusive exact row can be auto-selected");
  Expect(state.selected_playback_backend() ==
             aptt::BackendApi::kWasapiExclusive,
         "fresh accepted playback backend matches the requested backend");
}

void TestWasapiSharedMixFormatReferenceIsNotAutoSelected() {
  aptt::DiscoverySnapshot snapshot;
  snapshot.backend = aptt::BackendApi::kWasapiShared;

  aptt::DeviceInfo device;
  device.backend = aptt::BackendApi::kWasapiShared;
  device.display_name = "Fixture WASAPI endpoint";
  device.stable_id = "wasapi:{fixture-endpoint}";
  device.driver_name = "WASAPI/Core Audio";

  auto device_snapshot = aptt::MakeDiscoveredDeviceSnapshot(
      device,
      aptt::DeviceAvailability::kActive);
  aptt::CapabilityProbeRecord mix_format;
  mix_format.kind = aptt::CapabilityProbeKind::kFormatSupport;
  mix_format.support = aptt::CapabilitySupport::kSupported;
  mix_format.accepted_format = aptt::WasapiDefaultPcmCandidate();
  mix_format.backend_fields["api"] = "IAudioClient::GetMixFormat";
  device_snapshot.probes.push_back(mix_format);
  snapshot.devices.push_back(device_snapshot);

  aptt::DiagnosticUiState state;
  auto settings = state.settings();
  settings.requested_backend = aptt::BackendApi::kWasapiShared;
  state.UpdateSettings(settings);
  state.LoadProbeSnapshotForCurrentFormat(snapshot);
  Expect(state.SelectDiscoveredDeviceById("wasapi:{fixture-endpoint}"),
         "shared device selection succeeds");
  Expect(!state.selected_playback_format().has_value(),
         "shared GetMixFormat reference is not auto-selected");
}

void TestWasapiExclusiveMixFormatReferenceIsNotSelectable() {
  aptt::DiscoverySnapshot snapshot;
  snapshot.backend = aptt::BackendApi::kWasapiExclusive;

  aptt::DeviceInfo device;
  device.backend = aptt::BackendApi::kWasapiExclusive;
  device.display_name = "Fixture WASAPI endpoint";
  device.stable_id = "wasapi:{fixture-endpoint}";
  device.driver_name = "WASAPI/Core Audio";

  auto device_snapshot = aptt::MakeDiscoveredDeviceSnapshot(
      device,
      aptt::DeviceAvailability::kActive);
  aptt::CapabilityProbeRecord mix_format;
  mix_format.kind = aptt::CapabilityProbeKind::kFormatSupport;
  mix_format.support = aptt::CapabilitySupport::kSupported;
  mix_format.accepted_format = aptt::WasapiDefaultPcmCandidate();
  mix_format.backend_fields["api"] = "IAudioClient::GetMixFormat";
  device_snapshot.probes.push_back(mix_format);
  snapshot.devices.push_back(device_snapshot);

  aptt::DiagnosticUiState state;
  auto settings = state.settings();
  settings.requested_backend = aptt::BackendApi::kWasapiExclusive;
  state.UpdateSettings(settings);
  state.LoadProbeSnapshotForCurrentFormat(snapshot);
  Expect(state.SelectDiscoveredDeviceById("wasapi:{fixture-endpoint}"),
         "exclusive device selection succeeds");
  Expect(!state.SelectAcceptedFormatFromProbeIndex(0),
         "exclusive GetMixFormat reference row is not selectable");
  Expect(std::string_view(state.status_text()) == "mix format reference",
         "mix reference rejection has explicit status");
  Expect(!state.selected_playback_format().has_value(),
         "mix reference rejection does not store an accepted format");
}

void TestWasapiSharedFallbackCandidateRemainsSelectable() {
  aptt::DiscoverySnapshot snapshot;
  snapshot.backend = aptt::BackendApi::kWasapiShared;

  aptt::DeviceInfo device;
  device.backend = aptt::BackendApi::kWasapiShared;
  device.display_name = "Fixture WASAPI endpoint";
  device.stable_id = "wasapi:{fixture-endpoint}";
  device.driver_name = "WASAPI/Core Audio";

  auto device_snapshot = aptt::MakeDiscoveredDeviceSnapshot(
      device,
      aptt::DeviceAvailability::kActive);
  aptt::CapabilityProbeRecord mix_format;
  mix_format.kind = aptt::CapabilityProbeKind::kFormatSupport;
  mix_format.support = aptt::CapabilitySupport::kSupported;
  mix_format.accepted_format = aptt::WasapiDefaultPcmCandidate();
  mix_format.backend_fields["api"] = "IAudioClient::GetMixFormat";
  device_snapshot.probes.push_back(mix_format);

  aptt::CapabilityProbeRecord fallback;
  fallback.kind = aptt::CapabilityProbeKind::kFormatSupport;
  fallback.support = aptt::CapabilitySupport::kSupported;
  fallback.accepted_format = aptt::WasapiDefaultPcmCandidate();
  fallback.backend_fields["api"] = "IAudioClient::IsFormatSupported";
  fallback.backend_fields["candidate_label"] = "mix_format_fallback";
  device_snapshot.probes.push_back(fallback);
  snapshot.devices.push_back(device_snapshot);

  aptt::DiagnosticUiState state;
  state.LoadProbeSnapshotForCurrentFormat(snapshot);
  Expect(state.SelectDiscoveredDeviceById("wasapi:{fixture-endpoint}"),
         "shared device selection succeeds");
  Expect(state.SelectAcceptedFormatFromProbeIndex(1),
         "IsFormatSupported fallback row remains selectable");
  Expect(state.accepted_format_selection_kind() ==
             aptt::AcceptedFormatSelectionKind::kUserFallback,
         "fallback row is labeled as user fallback");
}

void TestExclusiveSelectionRequiresExactSupportedFormat() {
  aptt::DiscoverySnapshot snapshot;
  snapshot.backend = aptt::BackendApi::kWasapiExclusive;

  aptt::DeviceInfo device;
  device.backend = aptt::BackendApi::kWasapiExclusive;
  device.display_name = "Fixture WASAPI endpoint";
  device.stable_id = "wasapi:{fixture-endpoint}";
  device.driver_name = "WASAPI/Core Audio";

  auto device_snapshot = aptt::MakeDiscoveredDeviceSnapshot(
      device,
      aptt::DeviceAvailability::kActive);
  aptt::CapabilityProbeRecord closest;
  closest.kind = aptt::CapabilityProbeKind::kFormatSupport;
  closest.support = aptt::CapabilitySupport::kClosestMatch;
  closest.accepted_format = aptt::WasapiDefaultPcmCandidate();
  device_snapshot.probes.push_back(closest);
  snapshot.devices.push_back(device_snapshot);

  aptt::DiagnosticUiState state;
  auto settings = state.settings();
  settings.requested_backend = aptt::BackendApi::kWasapiExclusive;
  state.UpdateSettings(settings);
  state.LoadProbeSnapshotForCurrentFormat(snapshot);
  Expect(state.SelectDiscoveredDeviceById("wasapi:{fixture-endpoint}"),
         "exclusive device selection succeeds");
  Expect(!state.selected_playback_format().has_value(),
         "exclusive closest match is not treated as exact support");
}

void TestExclusiveSelectionStoresExactSupportedFormat() {
  aptt::DiscoverySnapshot snapshot;
  snapshot.backend = aptt::BackendApi::kWasapiExclusive;

  aptt::DeviceInfo device;
  device.backend = aptt::BackendApi::kWasapiExclusive;
  device.display_name = "Fixture WASAPI endpoint";
  device.stable_id = "wasapi:{fixture-endpoint}";
  device.driver_name = "WASAPI/Core Audio";

  auto device_snapshot = aptt::MakeDiscoveredDeviceSnapshot(
      device,
      aptt::DeviceAvailability::kActive);
  aptt::CapabilityProbeRecord supported;
  supported.kind = aptt::CapabilityProbeKind::kFormatSupport;
  supported.support = aptt::CapabilitySupport::kSupported;
  supported.accepted_format = aptt::WasapiDefaultPcmCandidate();
  supported.requested_format = supported.accepted_format;
  device_snapshot.probes.push_back(supported);
  snapshot.devices.push_back(device_snapshot);

  aptt::DiagnosticUiState state;
  auto settings = state.settings();
  settings.requested_backend = aptt::BackendApi::kWasapiExclusive;
  state.UpdateSettings(settings);
  state.LoadProbeSnapshotForCurrentFormat(snapshot);
  Expect(state.SelectDiscoveredDeviceById("wasapi:{fixture-endpoint}"),
         "exclusive device selection succeeds");
  Expect(state.selected_playback_format().has_value(),
         "exact exclusive format is stored after selection");
  Expect(state.selected_playback_backend() == aptt::BackendApi::kWasapiExclusive,
         "accepted format is associated with exclusive mode");
}

void TestExclusiveDopSelectionStoresExactCarrierFormat() {
  aptt::DiscoverySnapshot snapshot;
  snapshot.backend = aptt::BackendApi::kWasapiExclusive;

  aptt::DeviceInfo device;
  device.backend = aptt::BackendApi::kWasapiExclusive;
  device.display_name = "Fixture WASAPI DoP endpoint";
  device.stable_id = "wasapi:{fixture-dop-endpoint}";
  device.driver_name = "WASAPI/Core Audio";

  aptt::DopConfig dop;
  dop.dsd_rate_multiplier = 64;
  dop.channel_count = 2;

  auto device_snapshot = aptt::MakeDiscoveredDeviceSnapshot(
      device,
      aptt::DeviceAvailability::kActive);
  aptt::CapabilityProbeRecord mix_format;
  mix_format.kind = aptt::CapabilityProbeKind::kFormatSupport;
  mix_format.support = aptt::CapabilitySupport::kSupported;
  mix_format.accepted_format = aptt::WasapiDefaultPcmCandidate();
  mix_format.backend_fields["api"] = "IAudioClient::GetMixFormat";
  device_snapshot.probes.push_back(mix_format);

  aptt::CapabilityProbeRecord supported;
  supported.kind = aptt::CapabilityProbeKind::kFormatSupport;
  supported.support = aptt::CapabilitySupport::kSupported;
  supported.accepted_format = aptt::MakeDopCarrierFormat(dop);
  supported.requested_format = supported.accepted_format;
  supported.backend_fields["api"] = "IAudioClient::IsFormatSupported";
  device_snapshot.probes.push_back(supported);
  snapshot.devices.push_back(device_snapshot);

  aptt::DiagnosticUiState state;
  auto settings = state.settings();
  settings.requested_backend = aptt::BackendApi::kWasapiExclusive;
  settings.requested_signal = aptt::SignalMode::kDop;
  state.UpdateSettings(settings);
  state.LoadProbeSnapshotForCurrentFormat(snapshot);
  Expect(state.SelectDiscoveredDeviceById("wasapi:{fixture-dop-endpoint}"),
         "exclusive DoP device selection succeeds");
  Expect(state.selected_playback_format().has_value(),
         "exact DoP carrier is stored after selection");
  Expect(state.selected_playback_format()->signal_mode == aptt::SignalMode::kDop,
         "selected format is DoP");
  Expect(state.selected_playback_backend() == aptt::BackendApi::kWasapiExclusive,
         "DoP carrier is associated with exclusive mode");
}

void TestExclusiveStartRequiresSelectedDevice() {
  aptt::DiagnosticUiState state;
  state.StartWasapiExclusivePcm();

  Expect(!state.last_run_ok(), "exclusive playback without selection fails");
  Expect(std::string_view(state.status_text()) == "device not selected",
         "exclusive playback reports missing endpoint");
  Expect(!state.has_active_wasapi_exclusive_backend(),
         "no WASAPI exclusive backend is created without endpoint");
}

void TestWasapiDopProbeRequiresSelectedDevice() {
  aptt::DiagnosticUiState state;
  state.ProbeSelectedWasapiDopFormats();

  Expect(!state.last_run_ok(), "DoP probe without selection fails");
  Expect(std::string_view(state.status_text()) == "device not selected",
         "DoP probe reports missing endpoint");
  Expect(!state.log_lines().empty(), "DoP probe failure is logged");
}

void TestExclusivePcmStartRejectsDopCarrier() {
  aptt::DiscoverySnapshot snapshot;
  snapshot.backend = aptt::BackendApi::kWasapiExclusive;

  aptt::DeviceInfo device;
  device.backend = aptt::BackendApi::kWasapiExclusive;
  device.display_name = "Fixture WASAPI DoP endpoint";
  device.stable_id = "wasapi:{fixture-dop-endpoint}";
  device.driver_name = "WASAPI/Core Audio";

  aptt::DopConfig dop;
  dop.dsd_rate_multiplier = 64;
  dop.channel_count = 2;

  auto device_snapshot = aptt::MakeDiscoveredDeviceSnapshot(
      device,
      aptt::DeviceAvailability::kActive);
  aptt::CapabilityProbeRecord supported;
  supported.kind = aptt::CapabilityProbeKind::kFormatSupport;
  supported.support = aptt::CapabilitySupport::kSupported;
  supported.accepted_format = aptt::MakeDopCarrierFormat(dop);
  supported.requested_format = supported.accepted_format;
  device_snapshot.probes.push_back(supported);
  snapshot.devices.push_back(device_snapshot);

  aptt::DiagnosticUiState state;
  auto settings = state.settings();
  settings.requested_backend = aptt::BackendApi::kWasapiExclusive;
  settings.requested_signal = aptt::SignalMode::kDop;
  state.UpdateSettings(settings);
  state.LoadProbeSnapshotForCurrentFormat(snapshot);
  Expect(state.SelectDiscoveredDeviceById("wasapi:{fixture-dop-endpoint}"),
         "exclusive DoP device selection succeeds");
  state.StartWasapiExclusivePcm();

  Expect(!state.last_run_ok(), "PCM start rejects DoP carrier");
  Expect(std::string_view(state.status_text()) == "use DoP button",
         "PCM start tells the UI to use explicit DoP mode");
  Expect(!state.has_active_wasapi_exclusive_backend(),
         "PCM start does not create backend for DoP carrier");
}

void TestExclusiveDopStartRejectsPcmCarrier() {
  aptt::DiscoverySnapshot snapshot;
  snapshot.backend = aptt::BackendApi::kWasapiExclusive;

  aptt::DeviceInfo device;
  device.backend = aptt::BackendApi::kWasapiExclusive;
  device.display_name = "Fixture WASAPI endpoint";
  device.stable_id = "wasapi:{fixture-endpoint}";
  device.driver_name = "WASAPI/Core Audio";

  auto device_snapshot = aptt::MakeDiscoveredDeviceSnapshot(
      device,
      aptt::DeviceAvailability::kActive);
  aptt::CapabilityProbeRecord supported;
  supported.kind = aptt::CapabilityProbeKind::kFormatSupport;
  supported.support = aptt::CapabilitySupport::kSupported;
  supported.accepted_format = aptt::WasapiDefaultPcmCandidate();
  supported.requested_format = supported.accepted_format;
  device_snapshot.probes.push_back(supported);
  snapshot.devices.push_back(device_snapshot);

  aptt::DiagnosticUiState state;
  auto settings = state.settings();
  settings.requested_backend = aptt::BackendApi::kWasapiExclusive;
  state.UpdateSettings(settings);
  state.LoadProbeSnapshotForCurrentFormat(snapshot);
  Expect(state.SelectDiscoveredDeviceById("wasapi:{fixture-endpoint}"),
         "exclusive PCM device selection succeeds");
  state.StartWasapiExclusiveDop();

  Expect(!state.last_run_ok(), "DoP start rejects PCM carrier");
  Expect(std::string_view(state.status_text()) == "DoP carrier not accepted",
         "DoP start reports missing DoP carrier");
  Expect(!state.has_active_wasapi_exclusive_backend(),
         "DoP start does not create backend for PCM carrier");
}

void TestMmeFallbackRequiresExplicitAcceptedFormatSelection() {
  aptt::DiscoverySnapshot snapshot;
  snapshot.backend = aptt::BackendApi::kMme;

  aptt::DeviceInfo device;
  device.backend = aptt::BackendApi::kMme;
  device.display_name = "Fixture waveOut";
  device.stable_id = "mme:waveout:1";
  device.driver_name = "MME/waveOut";

  auto device_snapshot = aptt::MakeDiscoveredDeviceSnapshot(
      device,
      aptt::DeviceAvailability::kActive);
  device_snapshot.probes.push_back(aptt::MakeMmeFormatProbeRecord(
      aptt::MmePcmCandidate(48000, aptt::SampleType::kInt16, 2),
      0));
  snapshot.devices.push_back(device_snapshot);

  aptt::DiagnosticUiState state;
  auto settings = state.settings();
  settings.requested_backend = aptt::BackendApi::kMme;
  state.UpdateSettings(settings);
  state.LoadProbeSnapshotForCurrentFormat(snapshot);
  Expect(state.SelectDiscoveredDeviceById("mme:waveout:1"),
         "MME device selection succeeds");
  Expect(!state.selected_playback_format().has_value(),
         "MME fallback format is not auto-selected");
  Expect(state.SelectAcceptedFormatFromProbeIndex(0),
         "MME fallback can be explicitly selected");
  Expect(state.selected_playback_format().has_value(),
         "MME supported format is stored after explicit selection");
  Expect(state.selected_playback_backend() == aptt::BackendApi::kMme,
         "accepted format is associated with MME");
  Expect(state.accepted_format_selection_kind() ==
             aptt::AcceptedFormatSelectionKind::kUserFallback,
         "MME fallback selection is labeled as user fallback");
}

void TestMmeStartRequiresSelectedDevice() {
  aptt::DiagnosticUiState state;
  state.StartMmePcm();

  Expect(!state.last_run_ok(), "MME playback without selection fails");
  Expect(std::string_view(state.status_text()) == "device not selected",
         "MME playback reports missing device");
  Expect(!state.has_active_mme_backend(),
         "no MME backend is created without device");
}

void TestDirectSoundProbeRequiresSelectedDevice() {
  aptt::DiagnosticUiState state;
  state.ProbeSelectedDirectSoundFormats();

  Expect(!state.last_run_ok(), "DirectSound probe without selection fails");
  Expect(std::string_view(state.status_text()) == "device not selected",
         "DirectSound probe reports missing device");
  Expect(!state.log_lines().empty(),
         "DirectSound probe missing-device error is logged");
}

void TestDirectSoundFallbackRequiresExplicitAcceptedFormatSelection() {
  aptt::DiscoverySnapshot snapshot;
  snapshot.backend = aptt::BackendApi::kDirectSound;

  auto device_snapshot = aptt::MakeDirectSoundDeviceSnapshot(
      aptt::DirectSoundGuidStableIdFromText(
          "{01234567-89AB-CDEF-0123-456789ABCDEF}"),
      "Fixture DirectSound",
      "fixture.dll",
      false);
  device_snapshot.probes.push_back(aptt::MakeDirectSoundFormatProbeRecord(
      aptt::DirectSoundPcmCandidate(48000, aptt::SampleType::kInt16, 2),
      0));
  snapshot.devices.push_back(device_snapshot);

  aptt::DiagnosticUiState state;
  auto settings = state.settings();
  settings.requested_backend = aptt::BackendApi::kDirectSound;
  state.UpdateSettings(settings);
  state.LoadProbeSnapshotForCurrentFormat(snapshot);
  Expect(state.SelectDiscoveredDeviceById(
             "directsound:{01234567-89AB-CDEF-0123-456789ABCDEF}"),
         "DirectSound device selection succeeds");
  Expect(!state.selected_playback_format().has_value(),
         "DirectSound fallback format is not auto-selected");
  Expect(state.SelectAcceptedFormatFromProbeIndex(1),
         "DirectSound fallback can be explicitly selected");
  Expect(state.selected_playback_format().has_value(),
         "DirectSound supported format is stored after explicit selection");
  Expect(state.selected_playback_backend() == aptt::BackendApi::kDirectSound,
         "accepted format is associated with DirectSound");
  Expect(state.accepted_format_selection_kind() ==
             aptt::AcceptedFormatSelectionKind::kUserFallback,
         "DirectSound fallback selection is labeled as user fallback");
}

void TestDirectSoundStartRequiresSelectedDevice() {
  aptt::DiagnosticUiState state;
  state.StartDirectSoundPcm();

  Expect(!state.last_run_ok(), "DirectSound playback without selection fails");
  Expect(std::string_view(state.status_text()) == "device not selected",
         "DirectSound playback reports missing device");
  Expect(!state.has_active_directsound_backend(),
         "no DirectSound backend is created without device");
}

void TestPcmProbeFunctionsRejectNonPcmRequestedSignal() {
  {
    aptt::DiagnosticUiState state;
    auto settings = state.settings();
    settings.requested_backend = aptt::BackendApi::kMme;
    settings.requested_signal = aptt::SignalMode::kDop;
    state.UpdateSettings(settings);
    state.LoadDiscoverySnapshot(MakeMmeDeviceSnapshot());
    Expect(state.SelectDiscoveredDeviceById("mme:waveout:1"),
           "MME device selection succeeds");
    state.ProbeSelectedMmeFormats();
    Expect(!state.last_run_ok(),
           "MME PCM probe rejects non-PCM requested signal");
    Expect(std::string_view(state.status_text()) == "signal/backend mismatch",
           "MME PCM probe reports signal/backend mismatch");
    Expect(ContainsLine(state.log_lines(), "MME format probe blocked"),
           "MME PCM probe rejection is logged");
  }

  {
    aptt::DiagnosticUiState state;
    auto settings = state.settings();
    settings.requested_backend = aptt::BackendApi::kDirectSound;
    settings.requested_signal = aptt::SignalMode::kDop;
    state.UpdateSettings(settings);
    state.LoadDiscoverySnapshot(MakeDirectSoundDeviceSnapshot());
    Expect(state.SelectDiscoveredDeviceById(
               "directsound:{01234567-89AB-CDEF-0123-456789ABCDEF}"),
           "DirectSound device selection succeeds");
    state.ProbeSelectedDirectSoundFormats();
    Expect(!state.last_run_ok(),
           "DirectSound PCM probe rejects non-PCM requested signal");
    Expect(std::string_view(state.status_text()) == "signal/backend mismatch",
           "DirectSound PCM probe reports signal/backend mismatch");
  }

  {
    aptt::DiagnosticUiState state;
    auto settings = state.settings();
    settings.requested_backend = aptt::BackendApi::kWasapiShared;
    settings.requested_signal = aptt::SignalMode::kDop;
    state.UpdateSettings(settings);
    state.LoadDiscoverySnapshot(
        MakeWasapiPcmSnapshot(aptt::BackendApi::kWasapiShared));
    Expect(state.SelectDiscoveredDeviceById("wasapi:{fixture-endpoint}"),
           "WASAPI shared endpoint selection succeeds");
    state.ProbeSelectedWasapiFormats(false);
    Expect(!state.last_run_ok(),
           "WASAPI shared PCM probe rejects non-PCM requested signal");
    Expect(std::string_view(state.status_text()) == "signal/backend mismatch",
           "WASAPI shared PCM probe reports signal/backend mismatch");
  }

  {
    aptt::DiagnosticUiState state;
    auto settings = state.settings();
    settings.requested_backend = aptt::BackendApi::kWasapiExclusive;
    settings.requested_signal = aptt::SignalMode::kDop;
    state.UpdateSettings(settings);
    state.LoadDiscoverySnapshot(
        MakeWasapiPcmSnapshot(aptt::BackendApi::kWasapiExclusive));
    Expect(state.SelectDiscoveredDeviceById("wasapi:{fixture-endpoint}"),
           "WASAPI exclusive endpoint selection succeeds");
    state.ProbeSelectedWasapiFormats(true);
    Expect(!state.last_run_ok(),
           "WASAPI exclusive PCM probe rejects non-PCM requested signal");
    Expect(std::string_view(state.status_text()) == "signal/backend mismatch",
           "WASAPI exclusive PCM probe reports signal/backend mismatch");
  }

  {
    aptt::DiagnosticUiState state;
    auto settings = state.settings();
    settings.requested_backend = aptt::BackendApi::kAsio;
    settings.requested_signal = aptt::SignalMode::kDop;
    state.UpdateSettings(settings);
    state.LoadDiscoverySnapshot(MakeAsioDeviceSnapshot());
    Expect(state.SelectDiscoveredDeviceById(
               "asio:{01234567-89AB-CDEF-0123-456789ABCDEF}"),
           "ASIO driver selection succeeds");
    state.ProbeSelectedAsioPcmFormats();
    Expect(!state.last_run_ok(),
           "ASIO PCM probe rejects non-PCM requested signal");
    Expect(std::string_view(state.status_text()) == "signal/backend mismatch",
           "ASIO PCM probe reports signal/backend mismatch");
  }
}

void TestNativeDsdProbeRequiresAsioBackend() {
  {
    aptt::DiagnosticUiState state;
    auto settings = state.settings();
    settings.requested_backend = aptt::BackendApi::kMme;
    settings.requested_signal = aptt::SignalMode::kAsioNativeDsd;
    state.UpdateSettings(settings);
    state.LoadDiscoverySnapshot(MakeMmeDeviceSnapshot());
    Expect(state.SelectDiscoveredDeviceById("mme:waveout:1"),
           "MME device selection succeeds for native DSD guard");
    state.ProbeSelectedMmeFormats();
    Expect(!state.last_run_ok(), "native DSD + MME cannot probe");
    Expect(std::string_view(state.status_text()) == "signal/backend mismatch",
           "native DSD + MME reports signal/backend mismatch");
  }

  {
    aptt::DiagnosticUiState state;
    auto settings = state.settings();
    settings.requested_backend = aptt::BackendApi::kDirectSound;
    settings.requested_signal = aptt::SignalMode::kAsioNativeDsd;
    state.UpdateSettings(settings);
    state.LoadDiscoverySnapshot(MakeDirectSoundDeviceSnapshot());
    Expect(state.SelectDiscoveredDeviceById(
               "directsound:{01234567-89AB-CDEF-0123-456789ABCDEF}"),
           "DirectSound device selection succeeds for native DSD guard");
    state.ProbeSelectedDirectSoundFormats();
    Expect(!state.last_run_ok(),
           "native DSD + DirectSound cannot probe");
    Expect(std::string_view(state.status_text()) == "signal/backend mismatch",
           "native DSD + DirectSound reports signal/backend mismatch");
  }

  {
    aptt::DiagnosticUiState state;
    auto settings = state.settings();
    settings.requested_backend = aptt::BackendApi::kWasapiShared;
    settings.requested_signal = aptt::SignalMode::kAsioNativeDsd;
    state.UpdateSettings(settings);
    state.LoadDiscoverySnapshot(
        MakeWasapiPcmSnapshot(aptt::BackendApi::kWasapiShared));
    Expect(state.SelectDiscoveredDeviceById("wasapi:{fixture-endpoint}"),
           "WASAPI shared endpoint selection succeeds for native DSD guard");
    state.ProbeSelectedWasapiFormats(false);
    Expect(!state.last_run_ok(),
           "native DSD + WASAPI shared cannot probe");
    Expect(std::string_view(state.status_text()) == "signal/backend mismatch",
           "native DSD + WASAPI shared reports signal/backend mismatch");
  }

  {
    aptt::DiagnosticUiState state;
    auto settings = state.settings();
    settings.requested_backend = aptt::BackendApi::kWasapiExclusive;
    settings.requested_signal = aptt::SignalMode::kAsioNativeDsd;
    state.UpdateSettings(settings);
    state.LoadDiscoverySnapshot(
        MakeWasapiPcmSnapshot(aptt::BackendApi::kWasapiExclusive));
    Expect(state.SelectDiscoveredDeviceById("wasapi:{fixture-endpoint}"),
           "WASAPI exclusive endpoint selection succeeds for native DSD guard");
    state.ProbeSelectedWasapiFormats(true);
    Expect(!state.last_run_ok(),
           "native DSD + WASAPI exclusive cannot probe");
    Expect(std::string_view(state.status_text()) == "signal/backend mismatch",
           "native DSD + WASAPI exclusive reports signal/backend mismatch");
  }

  {
    aptt::DiagnosticUiState state;
    auto settings = state.settings();
    settings.requested_backend = aptt::BackendApi::kAsio;
    settings.requested_signal = aptt::SignalMode::kAsioNativeDsd;
    settings.requested_sample_type = aptt::SampleType::kDsd1BitLsbFirst;
    state.UpdateSettings(settings);
    state.LoadDiscoverySnapshot(MakeAsioDeviceSnapshot());
    Expect(state.SelectDiscoveredDeviceById(
               "asio:{01234567-89AB-CDEF-0123-456789ABCDEF}"),
           "ASIO device selection succeeds for native DSD probe");
    state.ProbeSelectedAsioNativeDsdFormats();
    Expect(std::string_view(state.status_text()) != "signal/backend mismatch",
           "native DSD + ASIO reaches the ASIO native DSD probe path");
    Expect(ContainsLine(state.log_lines(), "ASIO native DSD probe note"),
           "native DSD + ASIO records the native DSD probe note");
  }
}

void TestWasapiProbeModelGuardsRejectBackendMismatches() {
  {
    aptt::DiagnosticUiState state;
    auto settings = state.settings();
    settings.requested_backend = aptt::BackendApi::kMme;
    state.UpdateSettings(settings);
    state.LoadDiscoverySnapshot(MakeMmeDeviceSnapshot());
    Expect(state.SelectDiscoveredDeviceById("mme:waveout:1"),
           "MME device selection succeeds for WASAPI guard");
    state.ProbeSelectedWasapiFormats(false);
    Expect(!state.last_run_ok(),
           "WASAPI probe rejects selected MME device");
    Expect(std::string_view(state.status_text()) ==
               "WASAPI endpoint not selected",
           "WASAPI probe reports non-WASAPI selected device");
  }

  {
    aptt::DiagnosticUiState state;
    auto settings = state.settings();
    settings.requested_backend = aptt::BackendApi::kDirectSound;
    state.UpdateSettings(settings);
    state.LoadDiscoverySnapshot(MakeDirectSoundDeviceSnapshot());
    Expect(state.SelectDiscoveredDeviceById(
               "directsound:{01234567-89AB-CDEF-0123-456789ABCDEF}"),
           "DirectSound device selection succeeds for WASAPI guard");
    state.ProbeSelectedWasapiFormats(false);
    Expect(!state.last_run_ok(),
           "WASAPI probe rejects selected DirectSound device");
    Expect(std::string_view(state.status_text()) ==
               "WASAPI endpoint not selected",
           "WASAPI probe reports DirectSound is not a WASAPI endpoint");
  }

  {
    aptt::DiagnosticUiState state;
    auto settings = state.settings();
    settings.requested_backend = aptt::BackendApi::kWasapiShared;
    state.UpdateSettings(settings);
    state.LoadDiscoverySnapshot(
        MakeWasapiPcmSnapshot(aptt::BackendApi::kWasapiShared));
    Expect(state.SelectDiscoveredDeviceById("wasapi:{fixture-endpoint}"),
           "WASAPI shared endpoint selection succeeds");
    state.ProbeSelectedWasapiFormats(true);
    Expect(!state.last_run_ok(),
           "exclusive probe rejects shared requested backend");
    Expect(std::string_view(state.status_text()) == "signal/backend mismatch",
           "exclusive probe mismatch reports signal/backend mismatch");
  }

  {
    aptt::DiagnosticUiState state;
    auto settings = state.settings();
    settings.requested_backend = aptt::BackendApi::kWasapiExclusive;
    state.UpdateSettings(settings);
    state.LoadDiscoverySnapshot(
        MakeWasapiPcmSnapshot(aptt::BackendApi::kWasapiExclusive));
    Expect(state.SelectDiscoveredDeviceById("wasapi:{fixture-endpoint}"),
           "WASAPI exclusive endpoint selection succeeds");
    state.ProbeSelectedWasapiFormats(false);
    Expect(!state.last_run_ok(),
           "shared probe rejects exclusive requested backend");
    Expect(std::string_view(state.status_text()) == "signal/backend mismatch",
           "shared probe mismatch reports signal/backend mismatch");
  }

  {
    aptt::DiagnosticUiState state;
    auto settings = state.settings();
    settings.requested_backend = aptt::BackendApi::kWasapiExclusive;
    settings.requested_signal = aptt::SignalMode::kDop;
    state.UpdateSettings(settings);
    state.LoadDiscoverySnapshot(
        MakeWasapiPcmSnapshot(aptt::BackendApi::kWasapiExclusive));
    Expect(state.SelectDiscoveredDeviceById("wasapi:{fixture-endpoint}"),
           "WASAPI exclusive endpoint selection succeeds for DoP");
    state.ProbeSelectedWasapiDopFormats();
    Expect(std::string_view(state.status_text()) != "signal/backend mismatch",
           "exclusive DoP request reaches the WASAPI DoP probe path");
    Expect(ContainsLine(state.log_lines(), "DoP probe note"),
           "WASAPI DoP probe path logs the DoP probe note");
  }
}

void TestUiSettingsDefaultsAreConservative() {
  aptt::DiagnosticUiState state;
  const auto& settings = state.settings();

  Expect(settings.hold_mode == aptt::HoldMode::kKeepWarmAfterStop,
         "default hold mode is keep warm");
  Expect(settings.keep_alive_stream_enabled,
         "keep-alive stream is enabled by default");
  Expect(settings.drain_before_stop,
         "drain-before-stop is enabled by default");
  Expect(settings.rapid_format_cycle_guard,
         "rapid format cycling guard is enabled by default");
  Expect(!settings.expert_unsafe_release_ack,
         "unsafe release acknowledgement is not enabled by default");
  Expect(state.settings_warnings().empty(),
         "default UI settings have no warning without selected device");
}

void TestUiSettingsWarnForKnownProblemFullRelease() {
  aptt::DiagnosticUiState state;
  auto backend_settings = state.settings();
  backend_settings.requested_backend = aptt::BackendApi::kAsio;
  state.UpdateSettings(backend_settings);
  state.LoadProbeSnapshotForCurrentFormat(MakeAsioPcmSnapshot(true));
  Expect(state.SelectDiscoveredDeviceById(
             "asio:{01234567-89AB-CDEF-0123-456789ABCDEF}"),
         "known-problem ASIO device selection succeeds");

  auto settings = state.settings();
  settings.hold_mode = aptt::HoldMode::kReleaseAfterDrain;
  state.UpdateSettings(settings);

  const auto warnings = state.settings_warnings();
  Expect(ContainsLine(warnings, "known-problem device profile"),
         "known-problem full release warning is shown");
  Expect(ContainsLine(warnings, "release after drain"),
         "release-after-drain warning is shown");
}

void TestUnsafeReleaseBlocksKnownProblemStart() {
  aptt::DiagnosticUiState state;
  auto backend_settings = state.settings();
  backend_settings.requested_backend = aptt::BackendApi::kWasapiShared;
  state.UpdateSettings(backend_settings);
  state.LoadProbeSnapshotForCurrentFormat(MakeWasapiPcmSnapshot(
      aptt::BackendApi::kWasapiShared,
      "wasapi:{fixture-endpoint}",
      true));
  Expect(state.SelectDiscoveredDeviceById("wasapi:{fixture-endpoint}"),
         "known-problem WASAPI device selection succeeds");
  SelectMatrixCellForBackend(state,
                             aptt::BackendApi::kWasapiShared,
                             aptt::WasapiDefaultPcmCandidate());

  auto settings = state.settings();
  settings.hold_mode = aptt::HoldMode::kImmediateRelease;
  settings.expert_unsafe_release_ack = false;
  state.UpdateSettings(settings);
  state.StartWasapiSharedPcm();

  Expect(!state.last_run_ok(),
         "known-problem immediate release is blocked before start");
  Expect(std::string_view(state.status_text()) == "unsafe lifecycle settings",
         "unsafe lifecycle settings are reported");
  Expect(!state.has_active_wasapi_shared_backend(),
         "blocked unsafe start does not create WASAPI backend");
  Expect(ContainsLine(state.log_lines(), "blocked"),
         "unsafe start block is logged");
}

void TestStartLogsRequestedTroubleshootingSettings() {
  aptt::DiagnosticUiState state;
  auto backend_settings = state.settings();
  backend_settings.requested_backend = aptt::BackendApi::kWasapiShared;
  state.UpdateSettings(backend_settings);
  state.LoadProbeSnapshotForCurrentFormat(MakeWasapiPcmSnapshot(
      aptt::BackendApi::kWasapiShared));
  Expect(state.SelectDiscoveredDeviceById("wasapi:{fixture-endpoint}"),
         "WASAPI device selection succeeds");
  SelectMatrixCellForBackend(state,
                             aptt::BackendApi::kWasapiShared,
                             aptt::WasapiDefaultPcmCandidate());

  auto settings = state.settings();
  settings.frequency_hz = 1000.0;
  settings.amplitude_dbfs = -24.0;
  settings.duration_ms = 2500;
  settings.wasapi_shared_buffer_duration_ms = 64;
  settings.log_level = aptt::DiagnosticLogLevel::kVerbose;
  settings.left_channel_enabled = false;
  settings.right_channel_enabled = true;
  settings.invert_right_phase = true;
  settings.phase_offset_degrees = 90.0;
  const auto original_format_revision = state.format_revision();
  const auto original_run_config_revision = state.run_config_revision();
  state.UpdateSettings(settings);
  Expect(!state.accepted_format_is_stale(),
         "run-setting change does not mark the accepted format stale");
  Expect(state.format_revision() == original_format_revision,
         "run-setting change does not advance the format revision");
  Expect(state.run_config_revision() > original_run_config_revision,
         "run-setting change advances the run configuration revision");
  state.StartWasapiSharedPcm();

  Expect(ContainsLine(state.log_lines(), "amplitude_dbfs=-24"),
         "requested amplitude is logged before start");
  Expect(ContainsLine(state.log_lines(), "duration_ms=2500"),
         "requested duration is logged before start");
  Expect(ContainsLine(state.log_lines(), "wasapi_shared_buffer_ms=64"),
         "requested WASAPI shared buffer setting is logged before start");
  Expect(ContainsLine(state.log_lines(), "level=verbose"),
         "requested log level is logged before start");
  Expect(ContainsLine(state.log_lines(), "left_channel=off"),
         "left channel setting is logged before start");
  Expect(ContainsLine(state.log_lines(), "right_channel=on"),
         "right channel setting is logged before start");
  Expect(ContainsLine(state.log_lines(), "invert_right=true"),
         "right polarity setting is logged before start");
  Expect(ContainsLine(state.log_lines(), "right_phase_offset_degrees=90"),
         "right phase offset is logged before start");
}

void TestHighLoadDiagnosticsRequireExplicitAcknowledgement() {
  aptt::DiagnosticUiState state;
  Expect(!state.settings().high_load_diagnostics_enabled,
         "high-load diagnostics default off");
  Expect(!state.settings().high_load_risk_acknowledged,
         "high-load acknowledgement default off");

  auto backend_settings = state.settings();
  backend_settings.requested_backend = aptt::BackendApi::kWasapiShared;
  state.UpdateSettings(backend_settings);
  state.LoadProbeSnapshotForCurrentFormat(MakeWasapiPcmSnapshot(
      aptt::BackendApi::kWasapiShared));
  Expect(state.SelectDiscoveredDeviceById("wasapi:{fixture-endpoint}"),
         "WASAPI device selection succeeds for high-load gate test");
  SelectMatrixCellForBackend(state,
                             aptt::BackendApi::kWasapiShared,
                             aptt::WasapiDefaultPcmCandidate());

  auto settings = state.settings();
  const auto original_format_revision = state.format_revision();
  const auto original_run_config_revision = state.run_config_revision();
  settings.high_load_diagnostics_enabled = true;
  settings.high_load_risk_acknowledged = false;
  settings.high_load_render_delay_ms = 45;
  settings.high_load_delay_every_callbacks = 2;
  state.UpdateSettings(settings);

  Expect(state.format_revision() == original_format_revision,
         "high-load setting change does not invalidate format probes");
  Expect(state.run_config_revision() > original_run_config_revision,
         "high-load setting change advances run configuration revision");

  state.StartWasapiSharedPcm();
  Expect(!state.last_run_ok(),
         "high-load start without acknowledgement is blocked");
  Expect(ContainsLine(state.log_lines(),
                      "high-load diagnostics require explicit expert acknowledgement"),
         "high-load acknowledgement block is logged");

  settings = state.settings();
  settings.high_load_risk_acknowledged = true;
  state.UpdateSettings(settings);
  state.StartWasapiSharedPcm();

  Expect(ContainsLine(state.log_lines(), "high_load_mode=true"),
         "high-load mode is logged before start");
  Expect(ContainsLine(state.log_lines(), "high_load_mechanism=bounded_render_callback_delay"),
         "high-load mechanism is logged before start");
  Expect(ContainsLine(state.log_lines(), "high_load_delay_ms=45"),
         "high-load delay is logged before start");
  Expect(ContainsLine(state.log_lines(), "high_load_delay_every_callbacks=2"),
         "high-load callback cadence is logged before start");
  Expect(ContainsLine(state.log_lines(), "safety warning: high-load diagnostics"),
         "high-load safety warning is visible in logs");
}

void TestRequestedFormatsReflectUiSettings() {
  aptt::DiagnosticUiState state;
  auto settings = state.settings();
  settings.requested_sample_rate_hz = 96000;
  settings.requested_sample_type = aptt::SampleType::kInt24In32;
  settings.requested_valid_bits = 24;
  settings.requested_container_bits = 32;
  settings.requested_channel_count = 4;
  settings.requested_channel_mask = 0x33;
  settings.requested_dsd_rate_multiplier = 128;
  state.UpdateSettings(settings);

  const auto pcm = state.BuildRequestedPcmFormatFromSettings();
  Expect(pcm.signal_mode == aptt::SignalMode::kPcm,
         "requested PCM format has PCM signal mode");
  Expect(pcm.sample_rate_hz == 96000,
         "requested PCM format uses UI sample rate");
  Expect(pcm.sample_type == aptt::SampleType::kInt24In32,
         "requested PCM format uses UI sample type");
  Expect(pcm.valid_bits_per_sample == 24,
         "requested PCM format uses UI valid bits");
  Expect(pcm.container_bits_per_sample == 32,
         "requested PCM format uses UI container bits");
  Expect(pcm.channels.channel_count == 4,
         "requested PCM format uses UI channel count");
  Expect(pcm.channels.channel_mask == 0x33,
         "requested PCM format uses UI channel mask");

  const auto dop = state.BuildRequestedDopCarrierFromSettings();
  Expect(dop.signal_mode == aptt::SignalMode::kDop,
         "requested DoP format has DoP signal mode");
  Expect(dop.dsd_rate_multiplier &&
             *dop.dsd_rate_multiplier == 128,
         "requested DoP format uses UI DSD rate");
  Expect(dop.channels.channel_count == 4,
         "requested DoP format uses UI channel count");

  settings.requested_signal = aptt::SignalMode::kAsioNativeDsd;
  settings.requested_sample_type = aptt::SampleType::kDsd1BitMsbFirst;
  state.UpdateSettings(settings);
  const auto native_dsd = state.BuildRequestedNativeDsdFormatFromSettings();
  Expect(native_dsd.signal_mode == aptt::SignalMode::kAsioNativeDsd,
         "requested native DSD format has native DSD signal mode");
  Expect(native_dsd.sample_type == aptt::SampleType::kDsd1BitMsbFirst,
         "requested native DSD format uses UI sample type");
  Expect(native_dsd.dsd_rate_multiplier &&
             *native_dsd.dsd_rate_multiplier == 128,
         "requested native DSD format uses UI DSD rate");
}

void TestTickWithoutActiveBackendPreservesStats() {
  aptt::DiagnosticUiState state;
  state.RunNullSession();
  const auto frames_generated = state.stats().frames_generated;
  const auto callbacks = state.stats().callback_count;

  state.Tick();

  Expect(state.stats().frames_generated == frames_generated,
         "Tick without an active real backend preserves frame count");
  Expect(state.stats().callback_count == callbacks,
         "Tick without an active real backend preserves callback count");
  Expect(std::string_view(state.last_backend_error_summary()) == "none",
         "Tick without an active real backend does not invent errors");
}

void TestPlaybackCompletionStatusTextSeparatesSignalStopFromDeviceHold() {
  const auto running = aptt::PlaybackCompletionStatusText(
      aptt::BackendApi::kWasapiShared,
      aptt::DeviceLifecycleState::kRunningSignal);
  Expect(!running,
         "running signal does not report playback completion");

  const auto keep_alive = aptt::PlaybackCompletionStatusText(
      aptt::BackendApi::kWasapiShared,
      aptt::DeviceLifecycleState::kRunningSilence);
  Expect(keep_alive.has_value(),
         "running silence reports signal completion");
  Expect(keep_alive->find("signal stopped") != std::string::npos,
         "running silence status says the signal stopped");
  Expect(keep_alive->find("keep-alive") != std::string::npos,
         "running silence status says the stream is kept alive");

  const auto held_open = aptt::PlaybackCompletionStatusText(
      aptt::BackendApi::kWasapiExclusive,
      aptt::DeviceLifecycleState::kHeldOpen);
  Expect(held_open.has_value(),
         "held-open reports signal completion");
  Expect(held_open->find("held initialized") != std::string::npos,
         "held-open status says the stream remains initialized");
}

void TestActiveBackendLifecycleStateIsVisibleForUiGating() {
  aptt::DiagnosticUiState state;
  Expect(!state.active_backend_lifecycle_state().has_value(),
         "no active backend has no lifecycle state");
  Expect(!state.active_backend_api().has_value(),
         "no active backend has no backend API");

  state.InjectActiveBackendForTesting(aptt::BackendApi::kWasapiShared);
  const auto active_api = state.active_backend_api();
  Expect(active_api.has_value(),
         "injected active backend exposes a backend API");
  Expect(*active_api == aptt::BackendApi::kWasapiShared,
         "injected active backend API is preserved");
  const auto injected_state = state.active_backend_lifecycle_state();
  Expect(injected_state.has_value(),
         "injected active backend exposes a lifecycle state");
  Expect(*injected_state == aptt::DeviceLifecycleState::kRunningSignal,
         "injected active backend is treated as running signal");

  state.ClearInjectedActiveBackendForTesting();
  Expect(!state.active_backend_lifecycle_state().has_value(),
         "cleared injected backend has no lifecycle state");
}

void TestCloseGuardBlocksQuitWhileBackendIsActive() {
  const auto inactive =
      aptt::EvaluateAppCloseGuard(std::nullopt, std::nullopt, "none");
  Expect(!inactive.should_block_quit,
         "close guard allows quit with no active backend");

  aptt::DiagnosticUiState state;
  state.InjectActiveBackendForTesting(aptt::BackendApi::kDirectSound);
  const auto model_decision = state.app_close_guard_decision();
  Expect(model_decision.should_block_quit,
         "state close guard blocks quit while an active backend exists");
  Expect(!model_decision.has_kernel_streaming_release_timeout_warning,
         "generic active close guard is not the KS timeout warning");
  Expect(model_decision.japanese_message ==
             "\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",
         "generic close guard Japanese message matches support warning");
}

void TestCloseGuardUsesKernelStreamingReleaseTimeoutWarning() {
  const auto decision = aptt::EvaluateAppCloseGuard(
      std::optional<aptt::BackendApi>(aptt::BackendApi::kKernelStreaming),
      std::optional<aptt::DeviceLifecycleState>(
          aptt::DeviceLifecycleState::kFaulted),
      "Kernel Streaming error code=266245: "
      "\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\xBE\xE3\x81\x97\xE3\x81\x9F");
  Expect(decision.should_block_quit,
         "KS faulted release timeout blocks quit");
  Expect(decision.has_kernel_streaming_release_timeout_warning,
         "KS release timeout receives the stronger close warning");
  Expect(decision.japanese_message ==
             "\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",
         "KS timeout close guard Japanese message matches release-retry warning");
}

void TestSettingsChangeMarksAcceptedFormatStaleUntilReprobe() {
  aptt::DiagnosticUiState state;
  auto initial_settings = state.settings();
  initial_settings.requested_backend = aptt::BackendApi::kAsio;
  state.UpdateSettings(initial_settings);
  state.LoadProbeSnapshotForCurrentFormat(MakeAsioPcmSnapshot(false));
  Expect(state.SelectDiscoveredDeviceById(
             "asio:{01234567-89AB-CDEF-0123-456789ABCDEF}"),
         "ASIO exact format is selected");
  Expect(state.selected_playback_format().has_value(),
         "accepted format exists before settings change");
  Expect(!state.accepted_format_is_stale(),
         "accepted format is fresh immediately after exact probe");

  auto settings = state.settings();
  settings.requested_sample_rate_hz = 96000;
  state.UpdateSettings(settings);
  Expect(state.accepted_format_is_stale(),
         "sample-rate change marks accepted format stale");
  Expect(state.accepted_format_state_text() == "stale - probe again",
         "stale state is visible in UI model");
  Expect(state.accepted_format_state_text_japanese() ==
             "\xE5\x86\x8D\xE7\xA2\xBA\xE8\xAA\x8D\xE3\x81\x8C"
             "\xE5\xBF\x85\xE8\xA6\x81",
         "stale state has Japanese UI label");
  state.StartAsioPcm();
  Expect(!state.last_run_ok(), "stale accepted format blocks start");
  Expect(std::string_view(state.status_text()) == "format probe stale",
         "stale start rejection has explicit status");

  state.LoadProbeSnapshotForCurrentFormat(MakeAsioPcmSnapshot(false, 96000));
  Expect(state.SelectDiscoveredDeviceById(
             "asio:{01234567-89AB-CDEF-0123-456789ABCDEF}"),
         "ASIO exact format is selected after reprobe");
  Expect(!state.accepted_format_is_stale(),
         "reprobe clears stale accepted format state");
}

void TestStaleProbeRowsCannotBeReselectedAfterSampleRateChange() {
  aptt::DiagnosticUiState state;
  auto initial_settings = state.settings();
  initial_settings.requested_backend = aptt::BackendApi::kAsio;
  state.UpdateSettings(initial_settings);
  state.LoadProbeSnapshotForCurrentFormat(MakeAsioPcmSnapshot(false));
  Expect(state.SelectDiscoveredDeviceById(
             "asio:{01234567-89AB-CDEF-0123-456789ABCDEF}"),
         "ASIO exact 48 kHz format is selected");
  const auto accepted_revision =
      state.accepted_format_settings_revision();
  Expect(accepted_revision.has_value(),
         "accepted format records the probe revision");
  Expect(state.last_probe_format_revision() == accepted_revision,
         "probe rows are tied to the accepted format revision");

  auto settings = state.settings();
  settings.requested_sample_rate_hz = 96000;
  state.UpdateSettings(settings);
  Expect(state.last_probe_rows_are_stale(),
         "sample-rate change marks old probe rows stale");
  Expect(!state.SelectAcceptedFormatFromProbeIndex(0),
         "stale 48 kHz probe row cannot be selected");
  Expect(state.accepted_format_settings_revision() == accepted_revision,
         "stale row selection does not refresh accepted format revision");
  state.StartAsioPcm();
  Expect(!state.last_run_ok(),
         "start remains blocked after stale row selection attempt");
  Expect(std::string_view(state.status_text()) == "format probe stale",
         "stale start still reports stale probe");

  state.LoadProbeSnapshotForCurrentFormat(MakeAsioPcmSnapshot(false, 96000));
  Expect(state.SelectDiscoveredDeviceById(
             "asio:{01234567-89AB-CDEF-0123-456789ABCDEF}"),
         "new 96 kHz ASIO format is selected");
  Expect(!state.last_probe_rows_are_stale(),
         "new probe rows are fresh");
  Expect(state.selected_playback_format().has_value(),
         "new 96 kHz exact row is accepted normally");
  Expect(state.selected_playback_format()->sample_rate_hz == 96000,
         "accepted format follows the new 96 kHz request");
}

void TestDeviceReselectionDoesNotRefreshStaleProbeRows() {
  aptt::DiagnosticUiState state;
  auto initial_settings = state.settings();
  initial_settings.requested_backend = aptt::BackendApi::kAsio;
  state.UpdateSettings(initial_settings);
  state.LoadProbeSnapshotForCurrentFormat(MakeAsioPcmSnapshot(false));
  Expect(state.SelectDiscoveredDeviceById(
             "asio:{01234567-89AB-CDEF-0123-456789ABCDEF}"),
         "ASIO exact 48 kHz format is selected before reselect");

  auto settings = state.settings();
  settings.requested_sample_rate_hz = 96000;
  state.UpdateSettings(settings);
  Expect(state.last_probe_rows_are_stale(),
         "sample-rate change marks old probe rows stale before reselect");

  Expect(state.SelectDiscoveredDeviceById(
             "asio:{01234567-89AB-CDEF-0123-456789ABCDEF}"),
         "same device can be reselected from the old snapshot");
  Expect(state.last_probe_rows_are_stale(),
         "same-device reselection does not refresh old probe rows");
  Expect(!state.selected_playback_format().has_value(),
         "same-device reselection does not auto-select stale exact rows");
  Expect(!state.SelectAcceptedFormatFromProbeIndex(0),
         "same-device stale row still cannot be selected");
  state.StartAsioPcm();
  Expect(!state.last_run_ok(),
         "start remains blocked after same-device stale reselect");
  Expect(!state.has_active_asio_backend(),
         "same-device stale reselect does not open an ASIO backend");

  state.LoadProbeSnapshotForCurrentFormat(MakeAsioPcmSnapshot(false, 96000));
  Expect(state.SelectDiscoveredDeviceById(
             "asio:{01234567-89AB-CDEF-0123-456789ABCDEF}"),
         "fresh 96 kHz probe result can be selected");
  Expect(!state.last_probe_rows_are_stale(),
         "fresh probe rows clear stale state");
  Expect(state.selected_playback_format().has_value(),
         "fresh exact rows auto-select after a real probe result");
  Expect(state.selected_playback_format()->sample_rate_hz == 96000,
         "fresh accepted row uses the 96 kHz request");
}

void TestOtherDeviceSelectionDoesNotRefreshStaleProbeRows() {
  aptt::DiagnosticUiState state;
  auto initial_settings = state.settings();
  initial_settings.requested_backend = aptt::BackendApi::kAsio;
  state.UpdateSettings(initial_settings);
  state.LoadProbeSnapshotForCurrentFormat(MakeTwoDeviceAsioPcmSnapshot());
  Expect(state.SelectDiscoveredDeviceById(
             "asio:{01234567-89AB-CDEF-0123-456789ABCDEF}"),
         "first ASIO device is selected from a fresh multi-device probe");

  auto settings = state.settings();
  settings.requested_sample_rate_hz = 96000;
  state.UpdateSettings(settings);
  Expect(state.last_probe_rows_are_stale(),
         "old multi-device probe rows become stale after sample-rate change");

  Expect(state.SelectDiscoveredDeviceById(
             "asio:{22222222-3333-4444-5555-666666666666}"),
         "second ASIO device can be selected from the old snapshot");
  Expect(state.last_probe_rows_are_stale(),
         "other-device selection does not refresh old probe rows");
  Expect(!state.selected_playback_format().has_value(),
         "other-device selection does not auto-select stale exact rows");
  Expect(!state.SelectAcceptedFormatFromProbeIndex(0),
         "other-device stale row still cannot be selected");
  state.StartAsioPcm();
  Expect(!state.last_run_ok(),
         "start remains blocked after other-device stale selection");
  Expect(!state.has_active_asio_backend(),
         "other-device stale selection does not open an ASIO backend");
}

void TestStaleProbeRowsCannotBeReselectedAfterSignalModeChange() {
  aptt::DiagnosticUiState state;
  auto initial_settings = state.settings();
  initial_settings.requested_backend = aptt::BackendApi::kAsio;
  state.UpdateSettings(initial_settings);
  state.LoadProbeSnapshotForCurrentFormat(MakeAsioPcmSnapshot(false));
  Expect(state.SelectDiscoveredDeviceById(
             "asio:{01234567-89AB-CDEF-0123-456789ABCDEF}"),
         "ASIO PCM format is selected before signal change");
  const auto accepted_revision =
      state.accepted_format_settings_revision();

  auto settings = state.settings();
  settings.requested_signal = aptt::SignalMode::kAsioNativeDsd;
  settings.requested_sample_type = aptt::SampleType::kDsd1BitLsbFirst;
  state.UpdateSettings(settings);
  Expect(state.last_probe_rows_are_stale(),
         "signal-mode change marks old PCM probe rows stale");
  Expect(!state.SelectAcceptedFormatFromProbeIndex(0),
         "old PCM probe row cannot be selected for native DSD request");
  Expect(state.accepted_format_settings_revision() == accepted_revision,
         "stale signal-row selection does not refresh accepted revision");
  state.StartAsioPcm();
  Expect(!state.last_run_ok(),
         "old PCM start remains blocked after native DSD signal change");

  state.LoadProbeSnapshotForCurrentFormat(MakeAsioNativeDsdSnapshot());
  Expect(state.SelectDiscoveredDeviceById(
             "asio:{89ABCDEF-0123-4567-89AB-CDEF01234567}"),
         "new native DSD probe row is selected");
  Expect(!state.last_probe_rows_are_stale(),
         "native DSD probe rows are fresh");
  Expect(state.selected_playback_format().has_value(),
         "native DSD format is accepted after fresh probe");
  Expect(state.selected_playback_format()->signal_mode ==
             aptt::SignalMode::kAsioNativeDsd,
         "accepted fresh format is native DSD");
}

void TestDeviceReselectionDoesNotRefreshStaleRowsAfterSignalChange() {
  aptt::DiagnosticUiState state;
  auto initial_settings = state.settings();
  initial_settings.requested_backend = aptt::BackendApi::kAsio;
  state.UpdateSettings(initial_settings);
  state.LoadProbeSnapshotForCurrentFormat(MakeAsioPcmSnapshot(false));
  Expect(state.SelectDiscoveredDeviceById(
             "asio:{01234567-89AB-CDEF-0123-456789ABCDEF}"),
         "ASIO PCM format is selected before signal reselect test");

  auto settings = state.settings();
  settings.requested_signal = aptt::SignalMode::kAsioNativeDsd;
  settings.requested_sample_type = aptt::SampleType::kDsd1BitLsbFirst;
  state.UpdateSettings(settings);
  Expect(state.last_probe_rows_are_stale(),
         "native DSD signal change marks old PCM rows stale");

  Expect(state.SelectDiscoveredDeviceById(
             "asio:{01234567-89AB-CDEF-0123-456789ABCDEF}"),
         "same ASIO device can be reselected after signal change");
  Expect(state.last_probe_rows_are_stale(),
         "signal-change reselection does not refresh old PCM rows");
  Expect(!state.selected_playback_format().has_value(),
         "signal-change reselection does not auto-select old PCM rows");
  Expect(!state.SelectAcceptedFormatFromProbeIndex(0),
         "old PCM row cannot be selected for native DSD request after reselect");
  state.StartAsioNativeDsd();
  Expect(!state.last_run_ok(),
         "native DSD start remains blocked until a fresh DSD probe");
  Expect(!state.has_active_asio_native_dsd_backend(),
         "signal-change stale reselect does not open native DSD backend");
}

void TestRunConfigChangesDoNotMarkAcceptedFormatStale() {
  aptt::DiagnosticUiState state;
  auto initial_settings = state.settings();
  initial_settings.requested_backend = aptt::BackendApi::kAsio;
  state.UpdateSettings(initial_settings);
  state.LoadProbeSnapshotForCurrentFormat(MakeAsioPcmSnapshot(false));
  Expect(state.SelectDiscoveredDeviceById(
             "asio:{01234567-89AB-CDEF-0123-456789ABCDEF}"),
         "ASIO exact format is selected");

  const auto original_format_revision = state.format_revision();
  auto settings = state.settings();
  settings.amplitude_dbfs = -24.0;
  settings.duration_ms = 3000;
  settings.phase_offset_degrees = 45.0;
  state.UpdateSettings(settings);

  Expect(state.format_revision() == original_format_revision,
         "amplitude/duration/phase do not advance format revision");
  Expect(!state.accepted_format_is_stale(),
         "amplitude/duration/phase do not stale the accepted format");
  Expect(state.accepted_format_state_text_japanese() ==
             "\xE5\xAF\xBE\xE5\xBF\x9C\xE3\x82\xBB\xE3\x83\xAB"
             "\xE3\x82\x92\xE9\x81\xB8\xE6\x8A\x9E",
         "accepted format remains fresh in Japanese UI label");
}

void TestChannelAndSignalChangesMarkAcceptedFormatStale() {
  {
    aptt::DiagnosticUiState state;
    auto initial_settings = state.settings();
    initial_settings.requested_backend = aptt::BackendApi::kAsio;
    state.UpdateSettings(initial_settings);
    state.LoadProbeSnapshotForCurrentFormat(MakeAsioPcmSnapshot(false));
    Expect(state.SelectDiscoveredDeviceById(
               "asio:{01234567-89AB-CDEF-0123-456789ABCDEF}"),
           "ASIO exact format is selected for channel test");

    auto settings = state.settings();
    settings.requested_channel_count = 4;
    state.UpdateSettings(settings);
    Expect(state.accepted_format_is_stale(),
           "channel count change marks accepted format stale");
  }

  {
    aptt::DiagnosticUiState state;
    auto initial_settings = state.settings();
    initial_settings.requested_backend = aptt::BackendApi::kAsio;
    state.UpdateSettings(initial_settings);
    state.LoadProbeSnapshotForCurrentFormat(MakeAsioPcmSnapshot(false));
    Expect(state.SelectDiscoveredDeviceById(
               "asio:{01234567-89AB-CDEF-0123-456789ABCDEF}"),
           "ASIO exact format is selected for signal test");

    auto settings = state.settings();
    settings.requested_signal = aptt::SignalMode::kDop;
    state.UpdateSettings(settings);
    Expect(state.accepted_format_is_stale(),
           "signal mode change marks accepted format stale");
  }
}

void TestActiveBackendBlocksStateChangingActions() {
  aptt::DiagnosticUiState state;
  const auto original_format_revision = state.format_revision();
  const auto original_run_config_revision = state.run_config_revision();
  state.InjectActiveBackendForTesting(aptt::BackendApi::kWasapiShared);

  auto settings = state.settings();
  settings.expert_unsafe_release_ack = true;
  state.UpdateSettings(settings);
  Expect(state.settings().expert_unsafe_release_ack,
         "unsafe-release acknowledgement can be updated while active");
  Expect(state.format_revision() == original_format_revision,
         "release acknowledgement does not change format revision");
  Expect(state.run_config_revision() == original_run_config_revision,
         "release acknowledgement does not change run-config revision");
  Expect(ContainsLine(state.log_lines(), "release acknowledgement updated"),
         "active release acknowledgement update is logged");

  settings = state.settings();
  settings.requested_sample_rate_hz = 96000;
  state.UpdateSettings(settings);
  Expect(state.settings().requested_sample_rate_hz == 48000,
         "settings update is ignored while a backend is active");
  Expect(state.format_revision() == original_format_revision,
         "format revision does not change while active update is blocked");
  Expect(state.run_config_revision() == original_run_config_revision,
         "run-config revision does not change while active update is blocked");
  Expect(ContainsLine(state.log_lines(), "settings change blocked"),
         "blocked settings update is logged");

  state.RefreshAsioDrivers();
  Expect(state.discovery_snapshot().devices.empty(),
         "refresh does not replace discovery while active");
  Expect(ContainsLine(state.log_lines(), "ASIO refresh blocked"),
         "active refresh block is logged");

  state.RunNullSession();
  Expect(!state.has_exportable_diagnostic(),
         "Null run does not start while active backend is injected");

  state.ClearInjectedActiveBackendForTesting();
}

void TestSmokeArgumentParsingIsExact() {
  Expect(aptt::ContainsExactArgument({L"app.exe", L"--smoke"}, L"--smoke"),
         "exact --smoke argument is detected");
  Expect(!aptt::ContainsExactArgument({L"app.exe", L"--nosmoke"}, L"--smoke"),
         "--nosmoke does not trigger smoke mode");
  Expect(!aptt::ContainsExactArgument({L"app.exe", L"--smoke-extra"}, L"--smoke"),
         "prefix argument does not trigger smoke mode");
}

void TestAutomaticPlanRequiresSelectedDeviceAndFormat() {
  aptt::DiagnosticUiState state;
  state.PlanAutomaticSingleDeviceDiagnostic();

  Expect(!state.last_run_ok(), "automatic plan without selection fails");
  Expect(std::string_view(state.status_text()) == "automatic plan needs device",
         "automatic plan reports missing device");
  Expect(!state.last_automatic_plan().has_value(),
         "no automatic plan is stored without selection");
}

void TestAutomaticPlanRejectsKnownProblemFullRelease() {
  aptt::DiagnosticUiState state;
  auto backend_settings = state.settings();
  backend_settings.requested_backend = aptt::BackendApi::kAsio;
  state.UpdateSettings(backend_settings);
  state.LoadProbeSnapshotForCurrentFormat(MakeAsioPcmSnapshot(true));
  Expect(state.SelectDiscoveredDeviceById(
             "asio:{01234567-89AB-CDEF-0123-456789ABCDEF}"),
         "ASIO device selection succeeds");

  auto settings = state.settings();
  settings.hold_mode = aptt::HoldMode::kReleaseAfterDrain;
  settings.expert_unsafe_release_ack = true;
  state.UpdateSettings(settings);
  state.PlanAutomaticSingleDeviceDiagnostic();

  Expect(!state.last_run_ok(),
         "known-problem automatic plan rejects release-after-drain");
  Expect(state.last_automatic_plan().has_value(),
         "rejected automatic plan is stored for review");
  Expect(!state.last_automatic_plan()->rejection_reasons.empty(),
         "automatic plan records rejection reason");
}

void TestAutomaticRunProducesPlanAndScore() {
  const auto out = std::filesystem::current_path() / "ui_state_auto_output";
  std::filesystem::remove_all(out);

  aptt::DiagnosticUiState state;
  auto backend_settings = state.settings();
  backend_settings.requested_backend = aptt::BackendApi::kAsio;
  state.UpdateSettings(backend_settings);
  state.LoadProbeSnapshotForCurrentFormat(MakeAsioPcmSnapshot(false));
  Expect(state.SelectDiscoveredDeviceById(
             "asio:{01234567-89AB-CDEF-0123-456789ABCDEF}"),
         "ASIO device selection succeeds");
  auto settings = state.settings();
  settings.log_directory = out;
  settings.amplitude_dbfs = -24.0;
  state.UpdateSettings(settings);
  Expect(!state.accepted_format_is_stale(),
         "amplitude change does not require accepted format reprobe");

  state.RunAutomaticSingleDeviceDiagnostic();
  Expect(state.last_automatic_plan().has_value(),
         "automatic run stores a plan");
  Expect(state.last_automatic_plan()->accepted,
         "automatic run plan is accepted");
  Expect(state.last_diagnostic_score().has_value(),
         "automatic run stores a score");
  Expect(ContainsLine(state.log_lines(), "automatic diagnostic score="),
         "automatic score is logged");
}

void TestAutomaticRunBlocksPlanOnlyModes() {
  aptt::DiagnosticUiState state;
  auto backend_settings = state.settings();
  backend_settings.requested_backend = aptt::BackendApi::kAsio;
  state.UpdateSettings(backend_settings);
  state.LoadProbeSnapshotForCurrentFormat(MakeAsioPcmSnapshot(false));
  Expect(state.SelectDiscoveredDeviceById(
             "asio:{01234567-89AB-CDEF-0123-456789ABCDEF}"),
         "ASIO device selection succeeds");
  auto settings = state.settings();
  settings.automatic_format_matrix_enabled = true;
  state.UpdateSettings(settings);

  state.RunAutomaticSingleDeviceDiagnostic();
  Expect(!state.last_run_ok(),
         "automatic run blocks multi-step plan execution in this slice");
  Expect(std::string_view(state.status_text()) == "automatic plan only",
         "automatic run reports plan-only status");
}

void TestAsioRefreshIsSafeDryRun() {
  aptt::DiagnosticUiState state;
  auto settings = state.settings();
  settings.requested_backend = aptt::BackendApi::kAsio;
  state.UpdateSettings(settings);
  state.RefreshAsioDrivers();

  Expect(state.discovery_snapshot().backend == aptt::BackendApi::kAsio,
         "ASIO refresh stores ASIO snapshot");
  Expect(aptt::DiscoverySnapshotIsSafeDryRun(state.discovery_snapshot()),
         "ASIO refresh does not open drivers or start streams");
  Expect(!state.discovery_snapshot().devices.empty(),
         "ASIO refresh reports a status or driver record");
  Expect(!state.log_lines().empty(), "ASIO refresh is logged");
}

void TestKernelStreamingRefreshHonorsRequestedBackendGate() {
  aptt::DiagnosticUiState state;
  state.RefreshKernelStreamingDevices();

  Expect(!state.last_run_ok(),
         "Kernel Streaming refresh is blocked when target API is different");
  Expect(std::string_view(state.status_text()) == "signal/backend mismatch",
         "Kernel Streaming refresh reports target API mismatch");
  Expect(state.discovery_snapshot().backend == aptt::BackendApi::kNull,
         "Kernel Streaming refresh does not enumerate when backend is not selected");
}

void TestKernelStreamingProbeSnapshotDistinguishesCandidateAndVerifiedRows() {
  aptt::DiagnosticUiState state;
  auto settings = state.settings();
  settings.requested_backend = aptt::BackendApi::kKernelStreaming;
  state.UpdateSettings(settings);
  state.LoadProbeSnapshotForCurrentFormat(MakeKernelStreamingProbeSnapshot());
  Expect(state.SelectDiscoveredDeviceById(
             R"(ks:\\?\SWD#MMDEVAPI#{fixture-filter}#pin:3)"),
         "Kernel Streaming fixture device selection succeeds");
  const auto data_range_format =
      MakeTestPcmFormat(48000, aptt::SampleType::kFloat32, 32, 32, 2);
  const auto pin_verified_format =
      MakeTestPcmFormat(96000, aptt::SampleType::kFloat32, 32, 32, 2);
  Expect(!ContainsFormatForTest(
             state.last_format_probe().supported_formats,
             data_range_format),
         "Kernel Streaming data_range_match is not flattened into supported formats");
  Expect(ContainsFormatForTest(
             state.last_format_probe().supported_formats,
             pin_verified_format),
         "Kernel Streaming pin-created evidence remains a supported format");
  state.BuildDeviceCapabilityMatrix();

  Expect(state.device_capability_matrix().has_value(),
         "Kernel Streaming probe matrix is built");
  const auto& matrix = *state.device_capability_matrix();
  Expect(matrix.target_backend == aptt::BackendApi::kKernelStreaming,
         "Kernel Streaming matrix target is preserved");
  const auto row = FindMatrixRow(matrix, data_range_format);
  const auto column = FindMatrixColumn(matrix, 48000);
  Expect(row.has_value(), "Kernel Streaming PCM matrix row exists");
  Expect(column.has_value(), "Kernel Streaming PCM matrix column exists");

  const auto& cell = MatrixCell(matrix, *row, *column);
  Expect(cell.result_status == aptt::CapabilityCellStatus::kDataRangeMatch,
         "Kernel Streaming KSDATARANGE-only PCM probe is shown as a candidate");
  Expect(cell.selectable,
         "Kernel Streaming data-range candidate cell is selectable with warning");
  Expect(cell.raw_backend_fields.at("opens_filter") == "true",
         "Kernel Streaming probe cell records filter open");
  Expect(cell.raw_backend_fields.at("creates_pin") == "false",
         "Kernel Streaming automatic probe avoids repeated pin creation");
  Expect(cell.raw_backend_fields.at("ks_result_level") == "data_range_match",
         "Kernel Streaming data-range cell records the candidate result level");
  Expect(cell.raw_backend_fields.at("starts_stream") == "false",
         "Kernel Streaming probe cell records no stream start");
  Expect(state.SelectCapabilityMatrixCell(*row, *column),
         "Kernel Streaming candidate cell selection succeeds");
  Expect(state.selected_playback_format().has_value(),
         "Kernel Streaming candidate cell creates a playback format");
  Expect(state.selected_playback_backend() &&
             *state.selected_playback_backend() ==
                 aptt::BackendApi::kKernelStreaming,
         "Kernel Streaming selection records playback backend");

  const auto verified_row = FindMatrixRow(matrix, pin_verified_format);
  const auto verified_column = FindMatrixColumn(matrix, 96000);
  Expect(verified_row.has_value(), "Kernel Streaming pin-verified row exists");
  Expect(verified_column.has_value(),
         "Kernel Streaming pin-verified column exists");
  const auto& verified_cell =
      MatrixCell(matrix, *verified_row, *verified_column);
  Expect(verified_cell.result_status ==
             aptt::CapabilityCellStatus::kPinCreateVerified,
         "Kernel Streaming pin-create-verified row is distinguished");
  Expect(verified_cell.selectable,
         "Kernel Streaming pin-create-verified row remains selectable");
  Expect(verified_cell.raw_backend_fields.at("creates_pin") == "true",
         "Kernel Streaming pin-create-verified row records pin creation");

  aptt::DopConfig dop;
  dop.dsd_rate_multiplier = 64;
  dop.channel_count = 2;
  const auto dop_format = aptt::MakeDopCarrierFormat(dop);
  const auto dop_row = FindMatrixRow(matrix, dop_format);
  const auto dop_column =
      FindMatrixColumn(matrix, aptt::DopCarrierSampleRateHz(64));
  Expect(dop_row.has_value(), "Kernel Streaming DoP matrix row exists");
  Expect(dop_column.has_value(), "Kernel Streaming DoP matrix column exists");
  const auto& dop_cell = MatrixCell(matrix, *dop_row, *dop_column);
  Expect(dop_cell.result_status == aptt::CapabilityCellStatus::kDataRangeMatch,
         "Kernel Streaming accepted DoP carrier data range is a candidate");
  Expect(dop_cell.selectable,
         "Kernel Streaming DoP carrier candidate cell is selectable");
  Expect(state.SelectCapabilityMatrixCell(*dop_row, *dop_column),
         "Kernel Streaming DoP carrier cell selection succeeds");
  Expect(state.selected_playback_format() &&
             state.selected_playback_format()->signal_mode ==
                 aptt::SignalMode::kDop,
         "Kernel Streaming DoP selection stores a DoP carrier");
  Expect(state.selected_playback_backend() &&
             *state.selected_playback_backend() ==
                 aptt::BackendApi::kKernelStreaming,
         "Kernel Streaming DoP selection records playback backend");
}

void TestKernelStreamingNonPlaybackPinRowsAreNotSelectable() {
  aptt::DiagnosticUiState state;
  auto settings = state.settings();
  settings.requested_backend = aptt::BackendApi::kKernelStreaming;
  state.UpdateSettings(settings);
  const auto snapshot = MakeKernelStreamingNonPlaybackProbeSnapshot();
  const auto stable_id = snapshot.devices.front().device.stable_id;
  state.LoadProbeSnapshotForCurrentFormat(snapshot);
  Expect(state.SelectDiscoveredDeviceById(stable_id),
         "Kernel Streaming non-playback fixture device can be selected for inspection");
  state.BuildDeviceCapabilityMatrix();

  Expect(state.device_capability_matrix().has_value(),
         "Kernel Streaming non-playback probe matrix is built");
  const auto& matrix = *state.device_capability_matrix();
  const auto format =
      MakeTestPcmFormat(96000, aptt::SampleType::kInt16, 16, 16, 2);
  const auto row = FindMatrixRow(matrix, format);
  const auto column = FindMatrixColumn(matrix, 96000);
  Expect(row.has_value(), "Kernel Streaming non-playback PCM row exists");
  Expect(column.has_value(),
         "Kernel Streaming non-playback PCM column exists");

  const auto& cell = MatrixCell(matrix, *row, *column);
  Expect(!cell.selectable,
         "Kernel Streaming capture/non-playback pin cell is not selectable");
  Expect(cell.raw_backend_fields.at("ks_render_candidate") == "false",
         "Kernel Streaming non-playback cell records render candidate false");
  Expect(!state.SelectCapabilityMatrixCell(*row, *column),
         "Kernel Streaming non-playback matrix selection is rejected");
  Expect(!state.selected_playback_format().has_value(),
         "Kernel Streaming non-playback selection does not store a playback format");
}

void TestKernelStreamingLoopedRenderPinRowsAreDetectedButNotSelectable() {
  aptt::DiagnosticUiState state;
  auto settings = state.settings();
  settings.requested_backend = aptt::BackendApi::kKernelStreaming;
  state.UpdateSettings(settings);
  const auto snapshot = MakeKernelStreamingLoopedProbeSnapshot();
  const auto stable_id = snapshot.devices.front().device.stable_id;
  state.LoadProbeSnapshotForCurrentFormat(snapshot);
  Expect(state.SelectDiscoveredDeviceById(stable_id),
         "Kernel Streaming looped render fixture device can be selected");
  state.BuildDeviceCapabilityMatrix();

  Expect(state.device_capability_matrix().has_value(),
         "Kernel Streaming looped render probe matrix is built");
  const auto& matrix = *state.device_capability_matrix();
  const auto format =
      MakeTestPcmFormat(96000, aptt::SampleType::kInt16, 16, 16, 2);
  const auto row = FindMatrixRow(matrix, format);
  const auto column = FindMatrixColumn(matrix, 96000);
  Expect(row.has_value(), "Kernel Streaming looped PCM row exists");
  Expect(column.has_value(),
         "Kernel Streaming looped PCM column exists");

  const auto& cell = MatrixCell(matrix, *row, *column);
  Expect(cell.result_status == aptt::CapabilityCellStatus::kWarning,
         "Kernel Streaming looped data-range row is detected as unimplemented");
  Expect(!cell.selectable,
         "Kernel Streaming looped render candidate is not selectable until implemented");
  Expect(cell.raw_backend_fields.at("ks_stream_write_supported") == "false",
         "Kernel Streaming looped fixture records write-stream absence");
  Expect(cell.raw_backend_fields.at("ks_looped_streaming_supported") == "true",
         "Kernel Streaming looped fixture records looped interface support");
  Expect(cell.raw_backend_fields.at("ks_streaming_model") == "standard_looped",
         "Kernel Streaming looped fixture records the standard_looped model");
  Expect(cell.raw_backend_fields.at("ks_playback_implementation") ==
             "unimplemented",
         "Kernel Streaming looped fixture records unimplemented playback");
  Expect(!state.SelectCapabilityMatrixCell(*row, *column),
         "Kernel Streaming looped render matrix cell selection is rejected");
  Expect(!state.selected_playback_format().has_value(),
         "Kernel Streaming looped selection does not store playback format");
}

void TestKernelStreamingStreamingModelClassificationFixtures() {
  struct Case {
    const char* name;
    aptt::DiscoverySnapshot snapshot;
    aptt::CapabilityCellStatus expected_status;
    bool expected_selectable = false;
    const char* expected_model;
    const char* expected_standard;
    const char* expected_looped;
    const char* expected_wavert;
    const char* expected_accepts_wavert;
  };

  std::vector<Case> cases;
  cases.push_back({
      "standard only",
      MakeKernelStreamingModelProbeSnapshot(
          "standard_packet", true, false, "unknown"),
      aptt::CapabilityCellStatus::kDataRangeMatch,
      true,
      "standard_packet",
      "true",
      "false",
      "unknown",
      "unknown",
  });
  cases.push_back({
      "looped only",
      MakeKernelStreamingModelProbeSnapshot(
          "standard_looped", false, true, "unknown"),
      aptt::CapabilityCellStatus::kWarning,
      false,
      "standard_looped",
      "false",
      "true",
      "unknown",
      "unknown",
  });
  cases.push_back({
      "standard and looped",
      MakeKernelStreamingModelProbeSnapshot(
          "standard_packet", true, true, "unknown"),
      aptt::CapabilityCellStatus::kDataRangeMatch,
      true,
      "standard_packet",
      "true",
      "true",
      "unknown",
      "unknown",
  });
  cases.push_back({
      "WaveRT property only",
      MakeKernelStreamingModelProbeSnapshot(
          "standard_looped", false, true, "true"),
      aptt::CapabilityCellStatus::kWarning,
      false,
      "standard_looped",
      "false",
      "true",
      "true",
      "unknown",
  });
  cases.push_back({
      "WaveRT notification buffer accepted",
      MakeKernelStreamingModelProbeSnapshot(
          "wavert_cyclic",
          false,
          true,
          "true",
          aptt::CapabilitySupport::kSupported,
          "true"),
      aptt::CapabilityCellStatus::kDataRangeMatch,
      true,
      "wavert_cyclic",
      "false",
      "true",
      "true",
      "true",
  });
  cases.push_back({
      "unknown",
      MakeKernelStreamingModelProbeSnapshot(
          "unknown", false, false, "unknown",
          aptt::CapabilitySupport::kUnsupported),
      aptt::CapabilityCellStatus::kUnsupported,
      false,
      "unknown",
      "false",
      "false",
      "unknown",
      "unknown",
  });

  for (const auto& test_case : cases) {
    aptt::DiagnosticUiState state;
    auto settings = state.settings();
    settings.requested_backend = aptt::BackendApi::kKernelStreaming;
    state.UpdateSettings(settings);
    const auto stable_id = test_case.snapshot.devices.front().device.stable_id;
    state.LoadProbeSnapshotForCurrentFormat(test_case.snapshot);
    Expect(state.SelectDiscoveredDeviceById(stable_id),
           std::string("KS fixture device selection succeeds: ") +
               test_case.name);
    state.BuildDeviceCapabilityMatrix();
    Expect(state.device_capability_matrix().has_value(),
           std::string("KS fixture matrix exists: ") + test_case.name);
    const auto& matrix = *state.device_capability_matrix();
    const auto format =
        MakeTestPcmFormat(96000, aptt::SampleType::kInt16, 16, 16, 2);
    const auto row = FindMatrixRow(matrix, format);
    const auto column = FindMatrixColumn(matrix, 96000);
    Expect(row.has_value() && column.has_value(),
           std::string("KS fixture cell exists: ") + test_case.name);
    const auto& cell = MatrixCell(matrix, *row, *column);
    Expect(cell.result_status == test_case.expected_status,
           std::string("KS fixture status matches: ") + test_case.name);
    Expect(cell.selectable == test_case.expected_selectable,
           std::string("KS fixture selectable matches: ") + test_case.name);
    Expect(cell.raw_backend_fields.at("ks_streaming_model") ==
               test_case.expected_model,
           std::string("KS fixture model matches: ") + test_case.name);
    Expect(cell.raw_backend_fields.at("supports_standard_streaming") ==
               test_case.expected_standard,
           std::string("KS fixture standard flag matches: ") + test_case.name);
    Expect(cell.raw_backend_fields.at("supports_looped_streaming") ==
               test_case.expected_looped,
           std::string("KS fixture looped flag matches: ") + test_case.name);
    Expect(cell.raw_backend_fields.at("supports_wavert_rtaudio_properties") ==
               test_case.expected_wavert,
           std::string("KS fixture WaveRT flag matches: ") + test_case.name);
    Expect(cell.raw_backend_fields.at("accepts_wavert_notification_buffer") ==
               test_case.expected_accepts_wavert,
           std::string("KS fixture WaveRT notification-buffer flag matches: ") +
               test_case.name);
  }
}

void TestAsioProbeRequiresSelectedDriver() {
  aptt::DiagnosticUiState state;
  state.ProbeSelectedAsioPcmFormats();

  Expect(!state.last_run_ok(), "ASIO probe without selection fails");
  Expect(std::string_view(state.status_text()) == "device not selected",
         "ASIO probe reports missing selected driver");
  Expect(!state.log_lines().empty(), "ASIO probe missing-driver error is logged");
}

void TestAsioSelectionStoresSupportedPcmFormat() {
  aptt::DiscoverySnapshot snapshot;
  snapshot.backend = aptt::BackendApi::kAsio;

  aptt::DeviceInfo device;
  device.backend = aptt::BackendApi::kAsio;
  device.display_name = "Fixture ASIO Driver";
  device.driver_name = "Fixture ASIO Driver";
  device.stable_id = "asio:{01234567-89AB-CDEF-0123-456789ABCDEF}";
  device.is_known_problem_device = true;

  auto device_snapshot = aptt::MakeDiscoveredDeviceSnapshot(
      device,
      aptt::DeviceAvailability::kActive);
  aptt::CapabilityProbeRecord supported;
  supported.kind = aptt::CapabilityProbeKind::kFormatSupport;
  supported.support = aptt::CapabilitySupport::kSupported;
  supported.accepted_format = aptt::FormatDescriptor{};
  supported.accepted_format->signal_mode = aptt::SignalMode::kPcm;
  supported.accepted_format->sample_rate_hz = 48000;
  supported.accepted_format->sample_type = aptt::SampleType::kFloat32;
  supported.accepted_format->valid_bits_per_sample = 32;
  supported.accepted_format->container_bits_per_sample = 32;
  supported.accepted_format->channels.channel_count = 2;
  supported.accepted_format->channels.channel_mask = 3;
  supported.requested_format = supported.accepted_format;
  device_snapshot.probes.push_back(supported);
  snapshot.devices.push_back(device_snapshot);

  aptt::DiagnosticUiState state;
  auto settings = state.settings();
  settings.requested_backend = aptt::BackendApi::kAsio;
  state.UpdateSettings(settings);
  state.LoadProbeSnapshotForCurrentFormat(snapshot);
  Expect(state.SelectDiscoveredDeviceById(
             "asio:{01234567-89AB-CDEF-0123-456789ABCDEF}"),
         "ASIO device selection succeeds");
  Expect(state.selected_playback_format().has_value(),
         "ASIO supported PCM format is stored after selection");
  Expect(state.selected_playback_backend() == aptt::BackendApi::kAsio,
         "accepted format is associated with ASIO");
}

void TestAsioDopProbeRequiresSelectedDriver() {
  aptt::DiagnosticUiState state;
  state.ProbeSelectedAsioDopFormats();

  Expect(!state.last_run_ok(), "ASIO DoP probe without selection fails");
  Expect(std::string_view(state.status_text()) == "device not selected",
         "ASIO DoP probe reports missing selected driver");
  Expect(!state.log_lines().empty(),
         "ASIO DoP probe missing-driver error is logged");
}

void TestAsioSelectionStoresSupportedDopCarrierFormat() {
  aptt::DiscoverySnapshot snapshot;
  snapshot.backend = aptt::BackendApi::kAsio;

  aptt::DeviceInfo device;
  device.backend = aptt::BackendApi::kAsio;
  device.display_name = "Fixture ASIO DoP Driver";
  device.driver_name = "Fixture ASIO DoP Driver";
  device.stable_id = "asio:{13572468-2468-1357-2468-135724681357}";
  device.is_known_problem_device = true;

  aptt::DopConfig dop;
  dop.dsd_rate_multiplier = 64;
  dop.channel_count = 2;

  auto device_snapshot = aptt::MakeDiscoveredDeviceSnapshot(
      device,
      aptt::DeviceAvailability::kActive);
  aptt::CapabilityProbeRecord supported;
  supported.kind = aptt::CapabilityProbeKind::kFormatSupport;
  supported.support = aptt::CapabilitySupport::kSupported;
  supported.accepted_format = aptt::MakeDopCarrierFormat(dop);
  supported.requested_format = supported.accepted_format;
  supported.backend_fields["api"] = "ASIO DoP carrier query";
  supported.backend_fields["keep_alive_format"] = "valid-dop-silence";
  supported.backend_fields["opens_control_panel"] = "false";
  device_snapshot.probes.push_back(supported);
  snapshot.devices.push_back(device_snapshot);

  aptt::DiagnosticUiState state;
  auto settings = state.settings();
  settings.requested_backend = aptt::BackendApi::kAsio;
  settings.requested_signal = aptt::SignalMode::kDop;
  state.UpdateSettings(settings);
  state.LoadProbeSnapshotForCurrentFormat(snapshot);
  Expect(state.SelectDiscoveredDeviceById(
             "asio:{13572468-2468-1357-2468-135724681357}"),
         "ASIO DoP device selection succeeds");
  Expect(state.selected_playback_format().has_value(),
         "ASIO DoP carrier format is stored after selection");
  Expect(state.selected_playback_format()->signal_mode == aptt::SignalMode::kDop,
         "selected ASIO format is DoP");
  Expect(state.selected_playback_backend() == aptt::BackendApi::kAsio,
         "accepted DoP carrier is associated with ASIO");
}

void TestAsioPcmStartRejectsDopCarrier() {
  aptt::DiscoverySnapshot snapshot;
  snapshot.backend = aptt::BackendApi::kAsio;

  aptt::DeviceInfo device;
  device.backend = aptt::BackendApi::kAsio;
  device.display_name = "Fixture ASIO DoP Driver";
  device.driver_name = "Fixture ASIO DoP Driver";
  device.stable_id = "asio:{13572468-2468-1357-2468-135724681357}";

  aptt::DopConfig dop;
  dop.dsd_rate_multiplier = 64;
  dop.channel_count = 2;

  auto device_snapshot = aptt::MakeDiscoveredDeviceSnapshot(
      device,
      aptt::DeviceAvailability::kActive);
  aptt::CapabilityProbeRecord supported;
  supported.kind = aptt::CapabilityProbeKind::kFormatSupport;
  supported.support = aptt::CapabilitySupport::kSupported;
  supported.accepted_format = aptt::MakeDopCarrierFormat(dop);
  supported.requested_format = supported.accepted_format;
  device_snapshot.probes.push_back(supported);
  snapshot.devices.push_back(device_snapshot);

  aptt::DiagnosticUiState state;
  auto settings = state.settings();
  settings.requested_backend = aptt::BackendApi::kAsio;
  settings.requested_signal = aptt::SignalMode::kDop;
  state.UpdateSettings(settings);
  state.LoadProbeSnapshotForCurrentFormat(snapshot);
  Expect(state.SelectDiscoveredDeviceById(
             "asio:{13572468-2468-1357-2468-135724681357}"),
         "ASIO DoP device selection succeeds");
  state.StartAsioPcm();

  Expect(!state.last_run_ok(), "ASIO PCM start rejects DoP carrier");
  Expect(std::string_view(state.status_text()) == "use ASIO DoP button",
         "ASIO PCM start tells the UI to use explicit DoP mode");
  Expect(!state.has_active_asio_backend(),
         "ASIO PCM start does not create backend for DoP carrier");
}

void TestAsioDopStartRejectsPcmCarrier() {
  aptt::DiscoverySnapshot snapshot;
  snapshot.backend = aptt::BackendApi::kAsio;

  aptt::DeviceInfo device;
  device.backend = aptt::BackendApi::kAsio;
  device.display_name = "Fixture ASIO Driver";
  device.driver_name = "Fixture ASIO Driver";
  device.stable_id = "asio:{01234567-89AB-CDEF-0123-456789ABCDEF}";

  auto device_snapshot = aptt::MakeDiscoveredDeviceSnapshot(
      device,
      aptt::DeviceAvailability::kActive);
  aptt::CapabilityProbeRecord supported;
  supported.kind = aptt::CapabilityProbeKind::kFormatSupport;
  supported.support = aptt::CapabilitySupport::kSupported;
  supported.accepted_format = aptt::FormatDescriptor{};
  supported.accepted_format->signal_mode = aptt::SignalMode::kPcm;
  supported.accepted_format->sample_rate_hz = 48000;
  supported.accepted_format->sample_type = aptt::SampleType::kFloat32;
  supported.accepted_format->valid_bits_per_sample = 32;
  supported.accepted_format->container_bits_per_sample = 32;
  supported.accepted_format->channels.channel_count = 2;
  supported.accepted_format->channels.channel_mask = 3;
  supported.requested_format = supported.accepted_format;
  device_snapshot.probes.push_back(supported);
  snapshot.devices.push_back(device_snapshot);

  aptt::DiagnosticUiState state;
  auto settings = state.settings();
  settings.requested_backend = aptt::BackendApi::kAsio;
  state.UpdateSettings(settings);
  state.LoadProbeSnapshotForCurrentFormat(snapshot);
  Expect(state.SelectDiscoveredDeviceById(
             "asio:{01234567-89AB-CDEF-0123-456789ABCDEF}"),
         "ASIO PCM device selection succeeds");
  state.StartAsioDop();

  Expect(!state.last_run_ok(), "ASIO DoP start rejects PCM carrier");
  Expect(std::string_view(state.status_text()) == "ASIO DoP carrier not accepted",
         "ASIO DoP start reports missing exact carrier");
  Expect(!state.has_active_asio_backend(),
         "ASIO DoP start does not create backend for PCM format");
}

void TestAsioStartRequiresSelectedDriver() {
  aptt::DiagnosticUiState state;
  state.StartAsioPcm();

  Expect(!state.last_run_ok(), "ASIO playback without selection fails");
  Expect(std::string_view(state.status_text()) == "device not selected",
         "ASIO playback reports missing driver");
  Expect(!state.has_active_asio_backend(),
         "no ASIO backend is created without selected driver");
}

void TestAsioDopStartRequiresSelectedDriver() {
  aptt::DiagnosticUiState state;
  state.StartAsioDop();

  Expect(!state.last_run_ok(), "ASIO DoP playback without selection fails");
  Expect(std::string_view(state.status_text()) == "device not selected",
         "ASIO DoP playback reports missing driver");
  Expect(!state.has_active_asio_backend(),
         "no ASIO backend is created without selected driver");
}

void TestAsioStartFailsSafelyWhenBuildGateIsOff() {
#if !APTT_ENABLE_ASIO
  aptt::DiscoverySnapshot snapshot;
  snapshot.backend = aptt::BackendApi::kAsio;

  aptt::DeviceInfo device;
  device.backend = aptt::BackendApi::kAsio;
  device.display_name = "Fixture ASIO Driver";
  device.driver_name = "Fixture ASIO Driver";
  device.stable_id = "asio:{01234567-89AB-CDEF-0123-456789ABCDEF}";
  device.is_known_problem_device = true;

  auto device_snapshot = aptt::MakeDiscoveredDeviceSnapshot(
      device,
      aptt::DeviceAvailability::kActive);
  aptt::CapabilityProbeRecord supported;
  supported.kind = aptt::CapabilityProbeKind::kFormatSupport;
  supported.support = aptt::CapabilitySupport::kSupported;
  supported.accepted_format = aptt::FormatDescriptor{};
  supported.accepted_format->signal_mode = aptt::SignalMode::kPcm;
  supported.accepted_format->sample_rate_hz = 48000;
  supported.accepted_format->sample_type = aptt::SampleType::kFloat32;
  supported.accepted_format->valid_bits_per_sample = 32;
  supported.accepted_format->container_bits_per_sample = 32;
  supported.accepted_format->channels.channel_count = 2;
  supported.accepted_format->channels.channel_mask = 3;
  supported.requested_format = supported.accepted_format;
  device_snapshot.probes.push_back(supported);
  snapshot.devices.push_back(device_snapshot);

  aptt::DiagnosticUiState state;
  auto settings = state.settings();
  settings.requested_backend = aptt::BackendApi::kAsio;
  state.UpdateSettings(settings);
  state.LoadProbeSnapshotForCurrentFormat(snapshot);
  Expect(state.SelectDiscoveredDeviceById(
             "asio:{01234567-89AB-CDEF-0123-456789ABCDEF}"),
         "ASIO device selection succeeds");
  state.StartAsioPcm();

  Expect(!state.last_run_ok(), "ASIO start fails when build gate is OFF");
  Expect(std::string_view(state.status_text()) == "test condition not selected",
         "ASIO disabled start is blocked before driver reservation");
  Expect(!state.has_active_asio_backend(),
         "ASIO disabled start does not leave an active backend");
  Expect(!state.last_pcm_summary().has_value(),
         "ASIO disabled start does not create a run summary before test condition selection");
#endif
}

void TestAsioDopStartFailsSafelyWhenBuildGateIsOff() {
#if !APTT_ENABLE_ASIO
  aptt::DiscoverySnapshot snapshot;
  snapshot.backend = aptt::BackendApi::kAsio;

  aptt::DeviceInfo device;
  device.backend = aptt::BackendApi::kAsio;
  device.display_name = "Fixture ASIO DoP Driver";
  device.driver_name = "Fixture ASIO DoP Driver";
  device.stable_id = "asio:{13572468-2468-1357-2468-135724681357}";
  device.is_known_problem_device = true;

  aptt::DopConfig dop;
  dop.dsd_rate_multiplier = 64;
  dop.channel_count = 2;

  auto device_snapshot = aptt::MakeDiscoveredDeviceSnapshot(
      device,
      aptt::DeviceAvailability::kActive);
  aptt::CapabilityProbeRecord supported;
  supported.kind = aptt::CapabilityProbeKind::kFormatSupport;
  supported.support = aptt::CapabilitySupport::kSupported;
  supported.accepted_format = aptt::MakeDopCarrierFormat(dop);
  supported.requested_format = supported.accepted_format;
  supported.backend_fields["api"] = "ASIO DoP carrier query";
  supported.backend_fields["keep_alive_format"] = "valid-dop-silence";
  device_snapshot.probes.push_back(supported);
  snapshot.devices.push_back(device_snapshot);

  aptt::DiagnosticUiState state;
  auto settings = state.settings();
  settings.requested_backend = aptt::BackendApi::kAsio;
  settings.requested_signal = aptt::SignalMode::kDop;
  state.UpdateSettings(settings);
  state.LoadProbeSnapshotForCurrentFormat(snapshot);
  Expect(state.SelectDiscoveredDeviceById(
             "asio:{13572468-2468-1357-2468-135724681357}"),
         "ASIO DoP device selection succeeds");
  state.StartAsioDop();

  Expect(!state.last_run_ok(), "ASIO DoP start fails when build gate is OFF");
  Expect(std::string_view(state.status_text()) == "test condition not selected",
         "ASIO DoP disabled start is blocked before driver reservation");
  Expect(!state.has_active_asio_backend(),
         "ASIO DoP disabled start does not leave an active backend");
  Expect(!state.last_pcm_summary().has_value(),
         "ASIO DoP disabled start does not create a run summary before test condition selection");
#endif
}

void TestAsioNativeDsdProbeRequiresSelectedDriver() {
  aptt::DiagnosticUiState state;
  state.ProbeSelectedAsioNativeDsdFormats();

  Expect(!state.last_run_ok(), "ASIO native DSD probe without selection fails");
  Expect(std::string_view(state.status_text()) == "device not selected",
         "ASIO native DSD probe reports missing selected driver");
  Expect(!state.log_lines().empty(),
         "ASIO native DSD probe missing-driver error is logged");
}

void TestAsioNativeDsdSelectionStoresSupportedFormat() {
  aptt::DiscoverySnapshot snapshot;
  snapshot.backend = aptt::BackendApi::kAsio;

  aptt::DeviceInfo device;
  device.backend = aptt::BackendApi::kAsio;
  device.display_name = "Fixture ASIO DSD Driver";
  device.driver_name = "Fixture ASIO DSD Driver";
  device.stable_id = "asio:{89ABCDEF-0123-4567-89AB-CDEF01234567}";
  device.is_known_problem_device = true;

  aptt::NativeDsdConfig dsd;
  dsd.dsd_rate_multiplier = 64;
  dsd.channel_count = 2;
  dsd.sample_type = aptt::SampleType::kDsd1BitLsbFirst;

  auto device_snapshot = aptt::MakeDiscoveredDeviceSnapshot(
      device,
      aptt::DeviceAvailability::kActive);
  aptt::CapabilityProbeRecord supported;
  supported.kind = aptt::CapabilityProbeKind::kFormatSupport;
  supported.support = aptt::CapabilitySupport::kSupported;
  supported.accepted_format = aptt::MakeNativeDsdFormat(dsd);
  supported.requested_format = supported.accepted_format;
  supported.backend_fields["api"] = "ASIO native DSD query";
  supported.backend_fields["keep_alive_format"] = "valid-dsd-idle";
  device_snapshot.probes.push_back(supported);
  snapshot.devices.push_back(device_snapshot);

  aptt::DiagnosticUiState state;
  auto settings = state.settings();
  settings.requested_backend = aptt::BackendApi::kAsio;
  settings.requested_signal = aptt::SignalMode::kAsioNativeDsd;
  settings.requested_sample_type = aptt::SampleType::kDsd1BitLsbFirst;
  state.UpdateSettings(settings);
  state.LoadProbeSnapshotForCurrentFormat(snapshot);
  Expect(state.SelectDiscoveredDeviceById(
             "asio:{89ABCDEF-0123-4567-89AB-CDEF01234567}"),
         "ASIO native DSD device selection succeeds");
  Expect(state.selected_playback_format().has_value(),
         "ASIO native DSD supported format is stored after selection");
  Expect(state.selected_playback_format()->signal_mode ==
             aptt::SignalMode::kAsioNativeDsd,
         "selected ASIO format is native DSD");
  Expect(state.selected_playback_backend() == aptt::BackendApi::kAsio,
         "accepted native DSD format is associated with ASIO");
}

void TestAsioNativeDsdStartRequiresSelectedDriver() {
  aptt::DiagnosticUiState state;
  state.StartAsioNativeDsd();

  Expect(!state.last_run_ok(),
         "ASIO native DSD playback without selection fails");
  Expect(std::string_view(state.status_text()) == "device not selected",
         "ASIO native DSD playback reports missing driver");
  Expect(!state.has_active_asio_native_dsd_backend(),
         "no ASIO native DSD backend is created without selected driver");
}

void TestAsioNativeDsdStartFailsSafelyWhenBuildGateIsOff() {
#if !APTT_ENABLE_ASIO
  aptt::DiscoverySnapshot snapshot;
  snapshot.backend = aptt::BackendApi::kAsio;

  aptt::DeviceInfo device;
  device.backend = aptt::BackendApi::kAsio;
  device.display_name = "Fixture ASIO DSD Driver";
  device.driver_name = "Fixture ASIO DSD Driver";
  device.stable_id = "asio:{89ABCDEF-0123-4567-89AB-CDEF01234567}";
  device.is_known_problem_device = true;

  aptt::NativeDsdConfig dsd;
  dsd.dsd_rate_multiplier = 64;
  dsd.channel_count = 2;
  dsd.sample_type = aptt::SampleType::kDsd1BitLsbFirst;

  auto device_snapshot = aptt::MakeDiscoveredDeviceSnapshot(
      device,
      aptt::DeviceAvailability::kActive);
  aptt::CapabilityProbeRecord supported;
  supported.kind = aptt::CapabilityProbeKind::kFormatSupport;
  supported.support = aptt::CapabilitySupport::kSupported;
  supported.accepted_format = aptt::MakeNativeDsdFormat(dsd);
  supported.requested_format = supported.accepted_format;
  device_snapshot.probes.push_back(supported);
  snapshot.devices.push_back(device_snapshot);

  aptt::DiagnosticUiState state;
  auto settings = state.settings();
  settings.requested_backend = aptt::BackendApi::kAsio;
  settings.requested_signal = aptt::SignalMode::kAsioNativeDsd;
  settings.requested_sample_type = aptt::SampleType::kDsd1BitLsbFirst;
  state.UpdateSettings(settings);
  state.LoadProbeSnapshotForCurrentFormat(snapshot);
  Expect(state.SelectDiscoveredDeviceById(
             "asio:{89ABCDEF-0123-4567-89AB-CDEF01234567}"),
         "ASIO native DSD device selection succeeds");
  state.StartAsioNativeDsd();

  Expect(!state.last_run_ok(),
         "ASIO native DSD start fails when build gate is OFF");
  Expect(std::string_view(state.status_text()) == "test condition not selected",
         "ASIO native DSD disabled start is blocked before driver reservation");
  Expect(!state.has_active_asio_native_dsd_backend(),
         "ASIO native DSD disabled start does not leave an active backend");
#endif
}

}  // namespace

int main() {
  TestRunNullSessionUpdatesUiState();
  TestRunNullSessionCanWriteBundle();
  TestUiCanExportCurrentDiagnosticBundle();
  TestCanLoadAndSelectDiscoverySnapshotWithoutRealApi();
  TestDeviceFirstMatrixBuildDoesNotRequirePlaybackRoute();
  TestMatrixRowsPreserveCandidatesAndMarkUnsupportedCells();
  TestCapabilityScanChecksSelectedDeviceWithoutPriorProbeRows();
  TestSelectingUsableMatrixCellCreatesTestCondition();
  TestStartRequiresSelectedMatrixCondition();
  TestTargetDeviceChangeInvalidatesMatrixAndCondition();
  TestSignalSettingsDoNotInvalidateMatrix();
  TestDopAndNativeDsdMatrixGuards();
  TestMatrixRowsCoverWidePcmAndDsdRangesByDefault();
  TestReferenceMatrixCellsAreNotSelectable();
  TestWasapiModeSwitchCannotReuseStaleMatrixCells();
  TestWasapiFormatProbeRequiresSelectedDevice();
  TestWasapiSharedStartRequiresSelectedDevice();
  TestWasapiSharedStartRequiresAcceptedFormat();
  TestSelectionStoresAcceptedFormat();
  TestDiscoverySnapshotProbeRowsAreNotFreshWithoutProbeLoad();
  TestBackendChangeClearsIncompatibleSelectedDeviceAndFormat();
  TestWasapiBackendSwitchClearsEndpointAndAcceptedFormat();
  TestWasapiExclusiveToSharedSwitchMarksOldProbeRowsStale();
  TestWasapiModeSwitchFreshProbeRowsCanBeAccepted();
  TestWasapiSharedMixFormatReferenceIsNotAutoSelected();
  TestWasapiExclusiveMixFormatReferenceIsNotSelectable();
  TestWasapiSharedFallbackCandidateRemainsSelectable();
  TestExclusiveSelectionRequiresExactSupportedFormat();
  TestExclusiveSelectionStoresExactSupportedFormat();
  TestExclusiveDopSelectionStoresExactCarrierFormat();
  TestExclusiveStartRequiresSelectedDevice();
  TestWasapiDopProbeRequiresSelectedDevice();
  TestExclusivePcmStartRejectsDopCarrier();
  TestExclusiveDopStartRejectsPcmCarrier();
  TestMmeFallbackRequiresExplicitAcceptedFormatSelection();
  TestMmeStartRequiresSelectedDevice();
  TestDirectSoundProbeRequiresSelectedDevice();
  TestDirectSoundFallbackRequiresExplicitAcceptedFormatSelection();
  TestDirectSoundStartRequiresSelectedDevice();
  TestPcmProbeFunctionsRejectNonPcmRequestedSignal();
  TestNativeDsdProbeRequiresAsioBackend();
  TestWasapiProbeModelGuardsRejectBackendMismatches();
  TestUiSettingsDefaultsAreConservative();
  TestUiSettingsWarnForKnownProblemFullRelease();
  TestUnsafeReleaseBlocksKnownProblemStart();
  TestStartLogsRequestedTroubleshootingSettings();
  TestHighLoadDiagnosticsRequireExplicitAcknowledgement();
  TestRequestedFormatsReflectUiSettings();
  TestTickWithoutActiveBackendPreservesStats();
  TestPlaybackCompletionStatusTextSeparatesSignalStopFromDeviceHold();
  TestActiveBackendLifecycleStateIsVisibleForUiGating();
  TestCloseGuardBlocksQuitWhileBackendIsActive();
  TestCloseGuardUsesKernelStreamingReleaseTimeoutWarning();
  TestSettingsChangeMarksAcceptedFormatStaleUntilReprobe();
  TestStaleProbeRowsCannotBeReselectedAfterSampleRateChange();
  TestDeviceReselectionDoesNotRefreshStaleProbeRows();
  TestOtherDeviceSelectionDoesNotRefreshStaleProbeRows();
  TestStaleProbeRowsCannotBeReselectedAfterSignalModeChange();
  TestDeviceReselectionDoesNotRefreshStaleRowsAfterSignalChange();
  TestRunConfigChangesDoNotMarkAcceptedFormatStale();
  TestChannelAndSignalChangesMarkAcceptedFormatStale();
  TestActiveBackendBlocksStateChangingActions();
  TestSmokeArgumentParsingIsExact();
  TestAutomaticPlanRequiresSelectedDeviceAndFormat();
  TestAutomaticPlanRejectsKnownProblemFullRelease();
  TestAutomaticRunProducesPlanAndScore();
  TestAutomaticRunBlocksPlanOnlyModes();
  TestAsioRefreshIsSafeDryRun();
  TestKernelStreamingRefreshHonorsRequestedBackendGate();
  TestKernelStreamingProbeSnapshotDistinguishesCandidateAndVerifiedRows();
  TestKernelStreamingNonPlaybackPinRowsAreNotSelectable();
  TestKernelStreamingLoopedRenderPinRowsAreDetectedButNotSelectable();
  TestKernelStreamingStreamingModelClassificationFixtures();
  TestAsioProbeRequiresSelectedDriver();
  TestAsioSelectionStoresSupportedPcmFormat();
  TestAsioDopProbeRequiresSelectedDriver();
  TestAsioSelectionStoresSupportedDopCarrierFormat();
  TestAsioPcmStartRejectsDopCarrier();
  TestAsioDopStartRejectsPcmCarrier();
  TestAsioStartRequiresSelectedDriver();
  TestAsioDopStartRequiresSelectedDriver();
  TestAsioStartFailsSafelyWhenBuildGateIsOff();
  TestAsioDopStartFailsSafelyWhenBuildGateIsOff();
  TestAsioNativeDsdProbeRequiresSelectedDriver();
  TestAsioNativeDsdSelectionStoresSupportedFormat();
  TestAsioNativeDsdStartRequiresSelectedDriver();
  TestAsioNativeDsdStartFailsSafelyWhenBuildGateIsOff();

  std::cout << "diagnostic UI state tests passed\n";
  return 0;
}
