#include "backends/asio_native_dsd_backend.h"

#include <algorithm>
#include <array>
#include <atomic>
#include <chrono>
#include <cmath>
#include <cstring>
#include <limits>
#include <mutex>
#include <optional>
#include <sstream>
#include <thread>
#include <utility>

#include "backends/asio_driver_discovery.h"
#include "core/device_lifecycle.h"

#ifndef APTT_ENABLE_ASIO
#define APTT_ENABLE_ASIO 0
#endif

#if APTT_ENABLE_ASIO && defined(_WIN32)
#include "asiosys.h"
#include "asio.h"
#include "asiodrivers.h"

extern bool loadAsioDriver(char* name);
#endif

namespace aptt {
namespace {

constexpr int kAsioDsdInvalidArgument = 0xA53000;
constexpr int kAsioDsdDisabled = 0xA53001;
constexpr int kAsioDsdInvalidState = 0xA53002;
constexpr int kAsioDsdResetDisabled = 0xA53003;
constexpr int kAsioDsdDriverLoadFailed = 0xA53005;
constexpr int kAsioDsdDriverInitFailed = 0xA53006;
constexpr int kAsioDsdDriverQueryFailed = 0xA53007;
constexpr int kAsioDsdSampleRateFailed = 0xA53008;
constexpr int kAsioDsdBufferCreateFailed = 0xA53009;
constexpr int kAsioDsdUnsupportedSampleType = 0xA5300A;
constexpr int kAsioDsdStartFailed = 0xA5300B;
constexpr int kAsioDsdStopFailed = 0xA5300C;
constexpr int kAsioDsdDisposeFailed = 0xA5300D;
constexpr int kAsioDsdExitFailed = 0xA5300E;
constexpr int kAsioDsdIoFormatFailed = 0xA5300F;
constexpr int kAsioDsdNotImplemented =
    static_cast<int>(static_cast<std::int32_t>(0x80004001u));

struct AsioNativeDsdConstraints {
  long min_size = 0;
  long max_size = 0;
  long preferred_size = 0;
  long granularity = 0;
  long input_latency = 0;
  long output_latency = 0;
  bool output_ready_supported = false;
};

bool IsOneBitNativeDsd(SampleType sample_type) {
  return sample_type == SampleType::kDsd1BitLsbFirst ||
         sample_type == SampleType::kDsd1BitMsbFirst;
}

std::uint32_t NativeDsdBytesPerChannelFromSamples(
    std::int32_t buffer_samples,
    SampleType sample_type) {
  if (buffer_samples <= 0) {
    return 0;
  }
  const auto samples = static_cast<std::uint32_t>(buffer_samples);
  if (IsOneBitNativeDsd(sample_type)) {
    return samples / 8;
  }
  return samples;
}

std::uint64_t NativeDsdSamplesPerBuffer(std::uint32_t buffer_bytes_per_channel,
                                        SampleType sample_type) {
  if (IsOneBitNativeDsd(sample_type)) {
    return static_cast<std::uint64_t>(buffer_bytes_per_channel) * 8u;
  }
  return buffer_bytes_per_channel;
}

bool IsNativeDsdBufferAligned(std::int32_t buffer_samples,
                              SampleType sample_type) {
  if (!IsOneBitNativeDsd(sample_type)) {
    return true;
  }
  return buffer_samples > 0 && (buffer_samples % 8) == 0;
}

std::uint64_t DurationDsdSamples(const PlaybackConfig& config) {
  if (config.continuous) {
    return std::numeric_limits<std::uint64_t>::max();
  }
  const auto multiplier = config.format.dsd_rate_multiplier.value_or(64);
  return std::max<std::uint64_t>(
      1,
      (static_cast<std::uint64_t>(NativeDsdRateHz(multiplier)) *
       config.duration_ms) /
          1000);
}

NativeDsdConfig NativeDsdConfigFromFormat(const FormatDescriptor& format) {
  NativeDsdConfig config;
  config.dsd_rate_multiplier = format.dsd_rate_multiplier.value_or(64);
  config.channel_count = format.channels.channel_count == 0
      ? 1
      : format.channels.channel_count;
  config.sample_type = format.sample_type;
  return config;
}

std::string FormatSummary(const FormatDescriptor& format) {
  std::ostringstream summary;
  summary << format.sample_rate_hz << " Hz "
          << format.channels.channel_count << " ch "
          << ToString(format.sample_type) << " valid_bits="
          << format.valid_bits_per_sample << " container_bits="
          << format.container_bits_per_sample;
  if (format.dsd_rate_multiplier) {
    summary << " DSD" << *format.dsd_rate_multiplier;
  }
  return summary.str();
}

OperationResult ValidateConfigForAsioNativeDsd(const PlaybackConfig& config) {
  if (config.backend != BackendApi::kAsio) {
    return OperationResult::Failure(
        kAsioDsdInvalidArgument,
        "ASIO native DSD playback requires BackendApi::kAsio");
  }
  if (config.device.stable_id.empty() ||
      config.device.stable_id == "asio:disabled") {
    return OperationResult::Failure(
        kAsioDsdInvalidArgument,
        "ASIO native DSD playback requires an explicit ASIO driver ID");
  }
  if (!IsAsioNativeDsdPlaybackFormat(config.format)) {
    return OperationResult::Failure(
        kAsioDsdInvalidArgument,
        "ASIO native DSD playback requires a supported native DSD format");
  }
  const auto expected_rate =
      NativeDsdRateHz(config.format.dsd_rate_multiplier.value_or(0));
  if (expected_rate == 0 || config.format.sample_rate_hz != expected_rate ||
      config.format.channels.channel_count == 0) {
    return OperationResult::Failure(
        kAsioDsdInvalidArgument,
        "ASIO native DSD playback requires explicit DSD rate and channels");
  }
  return OperationResult::Success();
}

#if APTT_ENABLE_ASIO && defined(_WIN32)

class AsioNativeDsdCallbackSink {
 public:
  virtual ~AsioNativeDsdCallbackSink() = default;
  virtual void OnAsioBufferSwitch(long buffer_index,
                                  bool direct_process,
                                  bool has_time_info) = 0;
  virtual void OnAsioSampleRateChanged(double sample_rate) = 0;
  virtual long OnAsioMessage(long selector, long value) = 0;
};

std::mutex g_asio_dsd_callback_mutex;
AsioNativeDsdCallbackSink* g_asio_dsd_callback_sink = nullptr;

AsioNativeDsdCallbackSink* ActiveAsioNativeDsdCallbackSink() {
  std::lock_guard lock(g_asio_dsd_callback_mutex);
  return g_asio_dsd_callback_sink;
}

void SetActiveAsioNativeDsdCallbackSink(AsioNativeDsdCallbackSink* sink) {
  std::lock_guard lock(g_asio_dsd_callback_mutex);
  g_asio_dsd_callback_sink = sink;
}

void AsioNativeDsdBufferSwitch(long buffer_index, ASIOBool direct_process) {
  if (auto* sink = ActiveAsioNativeDsdCallbackSink()) {
    sink->OnAsioBufferSwitch(buffer_index, direct_process == ASIOTrue, false);
  }
}

ASIOTime* AsioNativeDsdBufferSwitchTimeInfo(ASIOTime* params,
                                            long buffer_index,
                                            ASIOBool direct_process) {
  if (auto* sink = ActiveAsioNativeDsdCallbackSink()) {
    sink->OnAsioBufferSwitch(buffer_index, direct_process == ASIOTrue, true);
  }
  return params;
}

void AsioNativeDsdSampleRateChanged(ASIOSampleRate sample_rate) {
  if (auto* sink = ActiveAsioNativeDsdCallbackSink()) {
    sink->OnAsioSampleRateChanged(static_cast<double>(sample_rate));
  }
}

long AsioNativeDsdMessages(long selector, long value, void*, double*) {
  if (auto* sink = ActiveAsioNativeDsdCallbackSink()) {
    return sink->OnAsioMessage(selector, value);
  }
  return 0;
}

std::optional<SampleType> AsioNativeDsdSampleTypeFromSdk(
    ASIOSampleType sample_type) {
  switch (sample_type) {
    case ASIOSTDSDInt8LSB1:
      return SampleType::kDsd1BitLsbFirst;
    case ASIOSTDSDInt8MSB1:
      return SampleType::kDsd1BitMsbFirst;
    case ASIOSTDSDInt8NER8:
      return SampleType::kDsd8Bit;
    default:
      return std::nullopt;
  }
}

const char* AsioErrorSymbol(ASIOError error) {
  switch (error) {
    case ASE_OK:
      return "ASE_OK";
    case ASE_NotPresent:
      return "ASE_NotPresent";
    case ASE_HWMalfunction:
      return "ASE_HWMalfunction";
    case ASE_InvalidParameter:
      return "ASE_InvalidParameter";
    case ASE_InvalidMode:
      return "ASE_InvalidMode";
    case ASE_SPNotAdvancing:
      return "ASE_SPNotAdvancing";
    case ASE_NoClock:
      return "ASE_NoClock";
    case ASE_NoMemory:
      return "ASE_NoMemory";
    default:
      return "ASE_Unknown";
  }
}

bool TryLoadAsioDriverName(const std::string& name) {
  if (name.empty()) {
    return false;
  }
  std::array<char, 128> driver_name{};
  const std::size_t bytes =
      std::min<std::size_t>(name.size(), driver_name.size() - 1);
  std::memcpy(driver_name.data(), name.data(), bytes);
  return loadAsioDriver(driver_name.data());
}

bool AsioFutureSucceeded(ASIOError error) {
  return error == ASE_SUCCESS;
}

bool IsAcceptedIoFormat(const ASIOIoFormat& format,
                        ASIOIoFormatType requested) {
  return format.FormatType == requested &&
         format.FormatType != kASIOFormatInvalid;
}

void CoolDownBeforeExplicitProbeExit() {
  std::this_thread::sleep_for(std::chrono::milliseconds(1000));
}

#endif

}  // namespace

AsioNativeDsdPolicy MakeAsioNativeDsdPolicy(const PlaybackConfig& config) {
  AsioNativeDsdPolicy policy;
  policy.keep_warm_after_signal =
      config.hold_mode == HoldMode::kKeepWarmAfterStop;
  policy.release_after_drain =
      config.hold_mode == HoldMode::kReleaseAfterDrain;
  policy.uses_output_ready_if_supported =
      config.asio_use_output_ready_if_supported;
  policy.release_cooldown_ms = config.release_cooldown_ms == 0
                                   ? 1
                                   : config.release_cooldown_ms;
  return policy;
}

bool IsAsioNativeDsdPlaybackFormat(const FormatDescriptor& format) {
  if (format.signal_mode != SignalMode::kAsioNativeDsd ||
      !format.dsd_rate_multiplier) {
    return false;
  }
  if (!IsSupportedNativeDsdRate(*format.dsd_rate_multiplier) ||
      !IsSupportedNativeDsdSampleType(format.sample_type)) {
    return false;
  }
  if (format.sample_type == SampleType::kDsd8Bit) {
    return format.valid_bits_per_sample == 8 &&
           format.container_bits_per_sample == 8;
  }
  return format.valid_bits_per_sample == 1 &&
         format.container_bits_per_sample == 8;
}

DiagnosticEvent MakeAsioNativeDsdPreparedEvent(
    std::uint64_t sequence,
    std::string device_id,
    const FormatDescriptor& format,
    std::uint32_t buffer_bytes_per_channel) {
  DiagnosticEvent event;
  event.type = DiagnosticEventType::kFormatProbe;
  event.sequence = sequence;
  event.backend = BackendApi::kAsio;
  event.device_id = std::move(device_id);
  event.format = format;
  event.message = "ASIO native DSD stream prepared";
  event.backend_fields["requested_format"] = FormatSummary(format);
  event.backend_fields["accepted_format"] = FormatSummary(format);
  event.backend_fields["signal_mode"] = ToString(format.signal_mode);
  event.backend_fields["native_dsd_sample_type"] =
      NativeDsdSampleTypeName(format.sample_type);
  event.backend_fields["native_dsd_byte_order"] =
      NativeDsdByteOrderName(format.sample_type);
  event.backend_fields["native_dsd_rate_multiplier"] =
      format.dsd_rate_multiplier
          ? std::to_string(*format.dsd_rate_multiplier)
          : "unknown";
  event.backend_fields["buffer_bytes_per_channel"] =
      std::to_string(buffer_bytes_per_channel);
  event.backend_fields["asio_io_format"] = "native-dsd";
  event.backend_fields["keep_alive_format"] = "valid-dsd-idle";
  event.backend_fields["opens_control_panel"] = "false";
  event.backend_fields["repeated_asio_exit"] = "false";
  return event;
}

DiagnosticEvent MakeAsioNativeDsdRuntimeEvent(
    std::uint64_t sequence,
    std::string device_id,
    const RealtimeStats& stats,
    std::int32_t buffer_index,
    std::uint32_t buffer_bytes_per_channel,
    bool idle_buffer) {
  DiagnosticEvent event;
  event.type = DiagnosticEventType::kRuntimeStats;
  event.sequence = sequence;
  event.backend = BackendApi::kAsio;
  event.device_id = std::move(device_id);
  event.message = "ASIO native DSD buffer update";
  event.realtime_stats = stats;
  event.backend_fields["buffer_index"] = std::to_string(buffer_index);
  event.backend_fields["buffer_bytes_per_channel"] =
      std::to_string(buffer_bytes_per_channel);
  event.backend_fields["idle_buffer"] = idle_buffer ? "true" : "false";
  event.backend_fields["keep_alive_format"] = "valid-dsd-idle";
  return event;
}

struct AsioNativeDsdBackend::Impl
#if APTT_ENABLE_ASIO && defined(_WIN32)
    : public AsioNativeDsdCallbackSink
#endif
{
  ~Impl() { Shutdown(); }

  BackendApi Api() const { return BackendApi::kAsio; }

  DeviceList EnumerateDevices() {
    DeviceList devices;
    const auto snapshot = EnumerateAsioDrivers();
    devices.reserve(snapshot.devices.size());
    for (const auto& device_snapshot : snapshot.devices) {
      devices.push_back(device_snapshot.device);
    }
    return devices;
  }

  FormatProbeResult ProbeFormats(const DeviceInfo& device,
                                 const NativeDsdConfig& requested_dsd) {
    FormatProbeResult result;
    result.requested = MakeNativeDsdFormat(requested_dsd);

    if (device.stable_id.empty() || device.stable_id == "asio:disabled") {
      result.rejection_reasons.push_back(
          "ASIO native DSD probe requires an explicit ASIO driver ID");
      return result;
    }
    if (!IsAsioSdkEnabled()) {
      result.rejection_reasons.push_back(
          "ASIO SDK integration is disabled at build time");
      return result;
    }

#if !(APTT_ENABLE_ASIO && defined(_WIN32))
    result.rejection_reasons.push_back(
        "ASIO native DSD probe is available only on Windows with ENABLE_ASIO");
    return result;
#else
    if (!TryLoadAsioDriverName(device.display_name) &&
        !TryLoadAsioDriverName(device.driver_name)) {
      result.rejection_reasons.push_back("ASIO driver could not be loaded");
      return result;
    }

    ASIODriverInfo driver_info{};
    driver_info.asioVersion = 2;
    ASIOError asio_result = ASIOInit(&driver_info);
    if (asio_result != ASE_OK) {
      result.rejection_reasons.push_back(
          "ASIOInit failed during native DSD probe");
      CoolDownBeforeExplicitProbeExit();
      ASIOExit();
      return result;
    }

    ASIOIoFormat dsd_format{};
    dsd_format.FormatType = kASIODSDFormat;
    asio_result = ASIOFuture(kAsioCanDoIoFormat, &dsd_format);
    if (!AsioFutureSucceeded(asio_result) ||
        !IsAcceptedIoFormat(dsd_format, kASIODSDFormat)) {
      result.rejection_reasons.push_back(
          "ASIO driver does not report native DSD I/O format support");
      CoolDownBeforeExplicitProbeExit();
      ASIOExit();
      return result;
    }

    dsd_format = {};
    dsd_format.FormatType = kASIODSDFormat;
    asio_result = ASIOFuture(kAsioSetIoFormat, &dsd_format);
    if (!AsioFutureSucceeded(asio_result) ||
        !IsAcceptedIoFormat(dsd_format, kASIODSDFormat)) {
      result.rejection_reasons.push_back(
          "ASIO driver rejected native DSD I/O format selection");
      CoolDownBeforeExplicitProbeExit();
      ASIOExit();
      return result;
    }

    long input_channels = 0;
    long output_channels = 0;
    asio_result = ASIOGetChannels(&input_channels, &output_channels);
    if (asio_result != ASE_OK || output_channels <= 0) {
      result.rejection_reasons.push_back(
          "ASIO driver reports no native DSD output channels");
      CoolDownBeforeExplicitProbeExit();
      ASIOExit();
      return result;
    }

    ASIOChannelInfo channel_info{};
    channel_info.channel = 0;
    channel_info.isInput = ASIOFalse;
    asio_result = ASIOGetChannelInfo(&channel_info);
    const auto sample_type = asio_result == ASE_OK
        ? AsioNativeDsdSampleTypeFromSdk(channel_info.type)
        : std::optional<SampleType>{};
    if (!sample_type) {
      result.rejection_reasons.push_back(
          "ASIO driver did not expose a supported native DSD sample type");
      CoolDownBeforeExplicitProbeExit();
      ASIOExit();
      return result;
    }

    if (output_channels < static_cast<long>(requested_dsd.channel_count)) {
      std::ostringstream reason;
      reason << "ASIO driver reports fewer native DSD output channels than requested: "
             << output_channels << " < " << requested_dsd.channel_count;
      result.rejection_reasons.push_back(reason.str());
      CoolDownBeforeExplicitProbeExit();
      ASIOExit();
      return result;
    }

    std::vector<std::uint32_t> requested_rates;
    requested_rates.push_back(requested_dsd.dsd_rate_multiplier);
    for (const auto rate_multiplier :
         {64u, 128u, 256u, 512u, 1024u, 2048u}) {
      if (std::find(requested_rates.begin(),
                    requested_rates.end(),
                    rate_multiplier) == requested_rates.end()) {
        requested_rates.push_back(rate_multiplier);
      }
    }
    for (const auto rate_multiplier : requested_rates) {
      const auto sample_rate = NativeDsdRateHz(rate_multiplier);
      if (ASIOCanSampleRate(static_cast<ASIOSampleRate>(sample_rate)) !=
          ASE_OK) {
        continue;
      }
      NativeDsdConfig accepted;
      accepted.dsd_rate_multiplier = rate_multiplier;
      accepted.channel_count = requested_dsd.channel_count;
      accepted.sample_type = *sample_type;
      result.supported_formats.push_back(MakeNativeDsdFormat(accepted));
    }

    if (result.supported_formats.empty()) {
      result.rejection_reasons.push_back(
          "ASIO driver native DSD sample type is supported, but no requested DSD rate was accepted");
    }

    CoolDownBeforeExplicitProbeExit();
    ASIOExit();
    return result;
#endif
  }

  OperationResult Initialize(const PlaybackConfig& config) {
    auto validation = ValidateConfigForAsioNativeDsd(config);
    if (!validation.ok) {
      SetLastError(validation.error);
      return validation;
    }
    if (!IsAsioSdkEnabled()) {
      return Fail(
          kAsioDsdDisabled,
          "ASIO native DSD playback is disabled because ENABLE_ASIO is OFF");
    }

    Shutdown();

    {
      std::scoped_lock lock(state_mutex_, stats_mutex_, events_mutex_);
      config_ = config;
      dsd_config_ = NativeDsdConfigFromFormat(config_.format);
      policy_ = MakeAsioNativeDsdPolicy(config_);
      stats_ = {};
      events_.clear();
      sequence_ = 0;
      lifecycle_state_ = DeviceLifecycleState::kDiscovered;
      constraints_ = {};
      buffer_bytes_per_channel_ = 0;
      signal_sample_target_ = DurationDsdSamples(config_);
      signal_samples_written_ = 0;
      force_idle_ = false;
      last_error_ = {};
      generator_.Reset();
    }

    if (!TransitionTo(DeviceLifecycleState::kReserved,
                      "selected ASIO driver reserved for native DSD")) {
      return OperationResult::Failure(kAsioDsdInvalidState,
                                      GetLastError().message);
    }

#if !(APTT_ENABLE_ASIO && defined(_WIN32))
    TransitionTo(DeviceLifecycleState::kFaulted,
                 "ASIO native DSD playback is not available");
    return Fail(
        kAsioDsdNotImplemented,
        "ASIO native DSD playback is available only on Windows with ENABLE_ASIO");
#else
    return InitializeAsioDriver();
#endif
  }

  OperationResult Start() {
#if !(APTT_ENABLE_ASIO && defined(_WIN32))
    return Fail(
        kAsioDsdDisabled,
        "ASIO native DSD playback is disabled because ENABLE_ASIO is OFF");
#else
    const auto current = GetState();
    if (current == DeviceLifecycleState::kRunningSilence) {
      return Fail(
          kAsioDsdInvalidState,
          "ASIO native DSD RunningSilence restart requires explicit release before rerun");
    }
    if (current != DeviceLifecycleState::kPrepared &&
        current != DeviceLifecycleState::kHeldOpen) {
      return Fail(kAsioDsdInvalidState,
                  "ASIO native DSD stream is not prepared");
    }
    if (!buffers_created_ || buffer_infos_.empty()) {
      return Fail(kAsioDsdInvalidState,
                  "ASIO native DSD buffers are not prepared");
    }

    force_idle_ = false;
    signal_samples_written_ = 0;
    generator_.Reset();
    last_callback_time_ = std::chrono::steady_clock::now();
    FillOutputBuffer(0, false, false, false);
    FillOutputBuffer(1, false, false, false);

    if (!TransitionTo(DeviceLifecycleState::kRunningSignal,
                      "ASIO 1 kHz native DSD signal started")) {
      return OperationResult::Failure(kAsioDsdInvalidState,
                                      GetLastError().message);
    }

    const ASIOError result = ASIOStart();
    if (result != ASE_OK) {
      TransitionTo(DeviceLifecycleState::kFaulted, "ASIOStart failed");
      AddErrorEvent(result, "ASIOStart",
                    "failed to start ASIO native DSD stream");
      return Fail(kAsioDsdStartFailed,
                  "failed to start ASIO native DSD stream");
    }
    started_ = true;
    return OperationResult::Success();
#endif
  }

  OperationResult Stop() {
    const auto current = GetState();
    if (current == DeviceLifecycleState::kRunningSignal &&
        policy_.keep_warm_after_signal) {
      force_idle_ = true;
      if (!TransitionTo(DeviceLifecycleState::kRunningSilence,
                        "normal ASIO native DSD stop switched to valid DSD idle keep-warm")) {
        return OperationResult::Failure(kAsioDsdInvalidState,
                                        GetLastError().message);
      }
      return OperationResult::Success();
    }
    if (current == DeviceLifecycleState::kRunningSilence &&
        policy_.keep_warm_after_signal) {
      return OperationResult::Success();
    }

#if APTT_ENABLE_ASIO && defined(_WIN32)
    if (current == DeviceLifecycleState::kRunningSignal ||
        current == DeviceLifecycleState::kRunningSilence) {
      if (!TransitionTo(DeviceLifecycleState::kDraining,
                        "ASIO native DSD stream stopping before hold/release")) {
        return OperationResult::Failure(kAsioDsdInvalidState,
                                        GetLastError().message);
      }
      const auto stop = StopAsioStream();
      if (!stop.ok) {
        return stop;
      }
    }
#endif

    if (policy_.release_after_drain) {
      return ReleaseAfterDrain();
    }
    if (GetState() != DeviceLifecycleState::kHeldOpen) {
      if (!TransitionTo(DeviceLifecycleState::kHeldOpen,
                        "ASIO native DSD driver held open after stop")) {
        return OperationResult::Failure(kAsioDsdInvalidState,
                                        GetLastError().message);
      }
    }
    return OperationResult::Success();
  }

  OperationResult Reset() {
    return Fail(
        kAsioDsdResetDisabled,
        "ASIO native DSD reset is disabled; use valid DSD idle keep-warm");
  }

  OperationResult Shutdown() {
    const auto current = GetState();
    if (current == DeviceLifecycleState::kDiscovered ||
        current == DeviceLifecycleState::kReleased) {
      return OperationResult::Success();
    }

    if (current == DeviceLifecycleState::kRunningSignal ||
        current == DeviceLifecycleState::kRunningSilence) {
      if (!TransitionTo(DeviceLifecycleState::kDraining,
                        "ASIO native DSD stream draining before release")) {
        return OperationResult::Failure(kAsioDsdInvalidState,
                                        GetLastError().message);
      }
    }
    return ReleaseAfterDrain();
  }

  RealtimeStats GetRealtimeStats() const {
    std::lock_guard lock(stats_mutex_);
    return stats_;
  }

  BackendError GetLastError() const {
    std::lock_guard lock(error_mutex_);
    return last_error_;
  }

  DeviceLifecycleState GetState() const {
    std::lock_guard lock(state_mutex_);
    return lifecycle_state_;
  }

  std::vector<DiagnosticEvent> GetEvents() const {
    std::lock_guard lock(events_mutex_);
    return events_;
  }

 private:
  OperationResult Fail(int code, std::string message) {
    SetLastError({code, std::move(message)});
    return OperationResult::Failure(code, GetLastError().message);
  }

  void SetLastError(BackendError error) {
    std::lock_guard lock(error_mutex_);
    last_error_ = std::move(error);
  }

  bool TransitionTo(DeviceLifecycleState next, std::string message) {
    DeviceLifecycleState previous;
    {
      std::lock_guard lock(state_mutex_);
      previous = lifecycle_state_;
      LifecyclePolicy lifecycle_policy;
      lifecycle_policy.known_problem_device =
          config_.device.is_known_problem_device;
      const auto decision = EvaluateTransition(previous, next, lifecycle_policy);
      if (!decision.allowed) {
        SetLastError({kAsioDsdInvalidState, decision.reason});
        return false;
      }
      lifecycle_state_ = next;
    }

    auto event = MakeLifecycleEvent(
        NextSequence(),
        BackendApi::kAsio,
        config_.device.stable_id,
        previous,
        next,
        std::move(message));
    event.backend_fields["hold_mode"] = ToString(config_.hold_mode);
    event.backend_fields["keep_alive_format"] = "valid-dsd-idle";
    event.backend_fields["asio_io_format"] = "native-dsd";
    event.backend_fields["reset_used"] = "false";
    event.backend_fields["repeated_asio_exit"] = "false";
    AppendEvent(std::move(event));
    SetLastError({});
    return true;
  }

  std::uint64_t NextSequence() { return ++sequence_; }

  void AppendEvent(DiagnosticEvent event) {
    std::lock_guard lock(events_mutex_);
    events_.push_back(std::move(event));
  }

  void AddPreparedEvent() {
    auto event = MakeAsioNativeDsdPreparedEvent(
        NextSequence(),
        config_.device.stable_id,
        config_.format,
        buffer_bytes_per_channel_);
    event.backend_fields["driver_name"] = config_.device.driver_name;
    event.backend_fields["output_channels"] = std::to_string(output_channels_);
    event.backend_fields["buffer_min"] = std::to_string(constraints_.min_size);
    event.backend_fields["buffer_max"] = std::to_string(constraints_.max_size);
    event.backend_fields["buffer_preferred"] =
        std::to_string(constraints_.preferred_size);
    event.backend_fields["buffer_granularity"] =
        std::to_string(constraints_.granularity);
    event.backend_fields["buffer_samples"] =
        std::to_string(constraints_.preferred_size);
    event.backend_fields["input_latency"] =
        std::to_string(constraints_.input_latency);
    event.backend_fields["output_latency"] =
        std::to_string(constraints_.output_latency);
    event.backend_fields["output_ready_supported"] =
        constraints_.output_ready_supported ? "true" : "false";
    event.backend_fields["sample_rate_set_result"] = sample_rate_set_result_;
    event.backend_fields["current_sample_rate"] =
        std::to_string(current_sample_rate_hz_);
    AppendEvent(std::move(event));
  }

  void AddRuntimeEvent(std::int32_t buffer_index,
                       double callback_duration_ms,
                       bool direct_process,
                       bool output_ready_called,
                       bool idle_buffer) {
    const auto stats = GetRealtimeStats();
    if (stats.callback_count > 8 && (stats.callback_count % 50) != 0) {
      return;
    }
    auto event = MakeAsioNativeDsdRuntimeEvent(
        NextSequence(),
        config_.device.stable_id,
        stats,
        buffer_index,
        buffer_bytes_per_channel_,
        idle_buffer);
    event.backend_fields["buffer_samples"] =
        std::to_string(constraints_.preferred_size);
    event.backend_fields["callback_duration_ms"] =
        std::to_string(callback_duration_ms);
    event.backend_fields["direct_process"] = direct_process ? "true" : "false";
    event.backend_fields["output_ready_called"] =
        output_ready_called ? "true" : "false";
    AppendEvent(std::move(event));
  }

  void AddErrorEvent(int code, std::string api, std::string message) {
    DiagnosticEvent event;
    event.type = DiagnosticEventType::kError;
    event.sequence = NextSequence();
    event.backend = BackendApi::kAsio;
    event.device_id = config_.device.stable_id;
    event.message = std::move(message);
    event.backend_fields["api"] = std::move(api);
    event.backend_fields["code"] = std::to_string(code);
#if APTT_ENABLE_ASIO && defined(_WIN32)
    event.backend_fields["symbol"] =
        AsioErrorSymbol(static_cast<ASIOError>(code));
#endif
    event.backend_fields["asio_io_format"] = "native-dsd";
    event.backend_fields["keep_alive_format"] = "valid-dsd-idle";
    event.backend_fields["repeated_asio_exit"] = "false";
    AppendEvent(std::move(event));
  }

  OperationResult ReleaseAfterDrain() {
    const auto current = GetState();
    if (current == DeviceLifecycleState::kFaulted) {
#if APTT_ENABLE_ASIO && defined(_WIN32)
      const auto release = ReleaseAsioResources();
      if (!release.ok) {
        return release;
      }
#endif
      if (!TransitionTo(DeviceLifecycleState::kReleased,
                        "faulted ASIO native DSD resources released once")) {
        return OperationResult::Failure(kAsioDsdInvalidState,
                                        GetLastError().message);
      }
      return OperationResult::Success();
    }

    if (current != DeviceLifecycleState::kReleasing &&
        current != DeviceLifecycleState::kReleased &&
        current != DeviceLifecycleState::kDiscovered) {
      if (!TransitionTo(DeviceLifecycleState::kReleasing,
                        "ASIO native DSD resources releasing after drain/cooldown")) {
        return OperationResult::Failure(kAsioDsdInvalidState,
                                        GetLastError().message);
      }
    }

    if (policy_.release_cooldown_ms > 0) {
      std::this_thread::sleep_for(
          std::chrono::milliseconds(policy_.release_cooldown_ms));
    }

#if APTT_ENABLE_ASIO && defined(_WIN32)
    const auto release = ReleaseAsioResources();
    if (!release.ok) {
      TransitionTo(DeviceLifecycleState::kFaulted,
                   "ASIO native DSD resource release failed");
      return release;
    }
#endif

    if (GetState() != DeviceLifecycleState::kReleased) {
      if (!TransitionTo(DeviceLifecycleState::kReleased,
                        "ASIO native DSD driver and buffers released once")) {
        return OperationResult::Failure(kAsioDsdInvalidState,
                                        GetLastError().message);
      }
    }
    return OperationResult::Success();
  }

#if APTT_ENABLE_ASIO && defined(_WIN32)
  OperationResult SetNativeDsdIoFormat() {
    ASIOIoFormat dsd_format{};
    dsd_format.FormatType = kASIODSDFormat;
    ASIOError result = ASIOFuture(kAsioCanDoIoFormat, &dsd_format);
    if (!AsioFutureSucceeded(result) ||
        !IsAcceptedIoFormat(dsd_format, kASIODSDFormat)) {
      AddErrorEvent(result, "ASIOFuture(kAsioCanDoIoFormat)",
                    "ASIO driver does not support native DSD I/O format");
      return Fail(kAsioDsdIoFormatFailed,
                  "ASIO driver does not support native DSD I/O format");
    }

    dsd_format = {};
    dsd_format.FormatType = kASIODSDFormat;
    result = ASIOFuture(kAsioSetIoFormat, &dsd_format);
    if (!AsioFutureSucceeded(result) ||
        !IsAcceptedIoFormat(dsd_format, kASIODSDFormat)) {
      AddErrorEvent(result, "ASIOFuture(kAsioSetIoFormat)",
                    "ASIO driver rejected native DSD I/O format");
      return Fail(kAsioDsdIoFormatFailed,
                  "ASIO driver rejected native DSD I/O format");
    }
    io_format_set_ = true;
    return OperationResult::Success();
  }

  OperationResult InitializeAsioDriver() {
    if (!TryLoadAsioDriverName(config_.device.display_name) &&
        !TryLoadAsioDriverName(config_.device.driver_name)) {
      TransitionTo(DeviceLifecycleState::kFaulted, "ASIO driver load failed");
      return Fail(kAsioDsdDriverLoadFailed,
                  "failed to load selected ASIO native DSD driver");
    }
    driver_loaded_ = true;

    driver_info_ = {};
    driver_info_.asioVersion = 2;
    const ASIOError init_result = ASIOInit(&driver_info_);
    if (init_result != ASE_OK) {
      TransitionTo(DeviceLifecycleState::kFaulted, "ASIOInit failed");
      AddErrorEvent(init_result, "ASIOInit",
                    "failed to initialize ASIO native DSD driver");
      ReleaseAsioResources();
      return Fail(kAsioDsdDriverInitFailed,
                  "failed to initialize ASIO native DSD driver");
    }

    const auto io_format = SetNativeDsdIoFormat();
    if (!io_format.ok) {
      TransitionTo(DeviceLifecycleState::kFaulted,
                   "ASIO native DSD I/O format setup failed");
      ReleaseAsioResources();
      return io_format;
    }

    long input_channels = 0;
    long output_channels = 0;
    ASIOError query_result = ASIOGetChannels(&input_channels, &output_channels);
    if (query_result != ASE_OK || output_channels <= 0 ||
        output_channels < static_cast<long>(config_.format.channels.channel_count)) {
      TransitionTo(DeviceLifecycleState::kFaulted, "ASIOGetChannels failed");
      AddErrorEvent(
          query_result,
          "ASIOGetChannels",
          "ASIO native DSD driver does not expose enough output channels");
      ReleaseAsioResources();
      return Fail(kAsioDsdDriverQueryFailed,
                  "ASIO native DSD driver does not expose enough output channels");
    }
    output_channels_ = output_channels;

    const ASIOSampleRate requested_rate =
        static_cast<ASIOSampleRate>(config_.format.sample_rate_hz);
    const ASIOError can_rate = ASIOCanSampleRate(requested_rate);
    if (can_rate != ASE_OK) {
      TransitionTo(DeviceLifecycleState::kFaulted, "ASIOCanSampleRate failed");
      AddErrorEvent(can_rate, "ASIOCanSampleRate",
                    "requested native DSD rate is not supported");
      ReleaseAsioResources();
      return Fail(kAsioDsdSampleRateFailed,
                  "requested native DSD rate is not supported");
    }

    ASIOSampleRate current_rate = 0.0;
    query_result = ASIOGetSampleRate(&current_rate);
    if (query_result != ASE_OK || current_rate <= 0.0) {
      TransitionTo(DeviceLifecycleState::kFaulted, "ASIOGetSampleRate failed");
      AddErrorEvent(query_result, "ASIOGetSampleRate",
                    "failed to query ASIO native DSD sample rate");
      ReleaseAsioResources();
      return Fail(kAsioDsdSampleRateFailed,
                  "failed to query ASIO native DSD sample rate");
    }
    current_sample_rate_hz_ = static_cast<double>(current_rate);
    sample_rate_set_result_ = "unchanged";
    if (std::llround(current_rate) !=
        static_cast<long long>(config_.format.sample_rate_hz)) {
      const ASIOError set_result = ASIOSetSampleRate(requested_rate);
      if (set_result != ASE_OK) {
        TransitionTo(DeviceLifecycleState::kFaulted, "ASIOSetSampleRate failed");
        AddErrorEvent(set_result, "ASIOSetSampleRate",
                      "failed to set requested ASIO native DSD rate");
        ReleaseAsioResources();
        return Fail(kAsioDsdSampleRateFailed,
                    "failed to set requested ASIO native DSD rate");
      }
      sample_rate_set_result_ = "set-once";
      current_sample_rate_hz_ =
          static_cast<double>(config_.format.sample_rate_hz);
    }

    query_result = ASIOGetBufferSize(
        &constraints_.min_size,
        &constraints_.max_size,
        &constraints_.preferred_size,
        &constraints_.granularity);
    if (query_result != ASE_OK || constraints_.preferred_size <= 0) {
      TransitionTo(DeviceLifecycleState::kFaulted, "ASIOGetBufferSize failed");
      AddErrorEvent(query_result, "ASIOGetBufferSize",
                    "failed to query ASIO native DSD buffer constraints");
      ReleaseAsioResources();
      return Fail(kAsioDsdDriverQueryFailed,
                  "failed to query ASIO native DSD buffer constraints");
    }
    if (!IsNativeDsdBufferAligned(
            constraints_.preferred_size,
            config_.format.sample_type)) {
      TransitionTo(DeviceLifecycleState::kFaulted,
                   "ASIO native DSD buffer size is not byte-aligned");
      ReleaseAsioResources();
      return Fail(
          kAsioDsdDriverQueryFailed,
          "ASIO native DSD 1-bit buffer size must be a multiple of 8 samples");
    }
    buffer_bytes_per_channel_ = NativeDsdBytesPerChannelFromSamples(
        constraints_.preferred_size,
        config_.format.sample_type);

    constraints_.output_ready_supported = ASIOOutputReady() == ASE_OK;
    callbacks_.bufferSwitch = &AsioNativeDsdBufferSwitch;
    callbacks_.sampleRateDidChange = &AsioNativeDsdSampleRateChanged;
    callbacks_.asioMessage = &AsioNativeDsdMessages;
    callbacks_.bufferSwitchTimeInfo = &AsioNativeDsdBufferSwitchTimeInfo;

    buffer_infos_.clear();
    buffer_infos_.resize(config_.format.channels.channel_count);
    for (std::uint32_t channel = 0; channel < config_.format.channels.channel_count;
         ++channel) {
      auto& info = buffer_infos_[channel];
      info.isInput = ASIOFalse;
      info.channelNum = static_cast<long>(channel);
      info.buffers[0] = nullptr;
      info.buffers[1] = nullptr;
    }

    SetActiveAsioNativeDsdCallbackSink(this);
    const ASIOError buffer_result = ASIOCreateBuffers(
        buffer_infos_.data(),
        static_cast<long>(buffer_infos_.size()),
        constraints_.preferred_size,
        &callbacks_);
    if (buffer_result != ASE_OK) {
      SetActiveAsioNativeDsdCallbackSink(nullptr);
      TransitionTo(DeviceLifecycleState::kFaulted,
                   "ASIOCreateBuffers failed");
      AddErrorEvent(buffer_result, "ASIOCreateBuffers",
                    "failed to create ASIO native DSD output buffers");
      ReleaseAsioResources();
      return Fail(kAsioDsdBufferCreateFailed,
                  "failed to create ASIO native DSD output buffers");
    }
    buffers_created_ = true;

    channel_infos_.clear();
    channel_infos_.resize(buffer_infos_.size());
    for (std::size_t index = 0; index < buffer_infos_.size(); ++index) {
      auto& info = channel_infos_[index];
      info.channel = buffer_infos_[index].channelNum;
      info.isInput = ASIOFalse;
      const ASIOError channel_result = ASIOGetChannelInfo(&info);
      if (channel_result != ASE_OK) {
        TransitionTo(DeviceLifecycleState::kFaulted,
                     "ASIOGetChannelInfo failed");
        AddErrorEvent(channel_result, "ASIOGetChannelInfo",
                      "failed to query ASIO native DSD output sample type");
        ReleaseAsioResources();
        return Fail(kAsioDsdDriverQueryFailed,
                    "failed to query ASIO native DSD output sample type");
      }
      const auto sample_type = AsioNativeDsdSampleTypeFromSdk(info.type);
      if (!sample_type) {
        TransitionTo(DeviceLifecycleState::kFaulted,
                     "unsupported ASIO native DSD sample type");
        AddErrorEvent(static_cast<int>(info.type), "ASIOGetChannelInfo",
                      "unsupported ASIO native DSD sample type");
        ReleaseAsioResources();
        return Fail(kAsioDsdUnsupportedSampleType,
                    "unsupported ASIO native DSD sample type");
      }
      if (!asio_sample_type_) {
        asio_sample_type_ = sample_type;
      } else if (*asio_sample_type_ != *sample_type) {
        TransitionTo(DeviceLifecycleState::kFaulted,
                     "mixed ASIO native DSD sample types are not supported");
        ReleaseAsioResources();
        return Fail(kAsioDsdUnsupportedSampleType,
                    "mixed ASIO native DSD sample types are not supported");
      }
    }

    if (!asio_sample_type_ ||
        *asio_sample_type_ != config_.format.sample_type) {
      TransitionTo(DeviceLifecycleState::kFaulted,
                   "selected native DSD sample type does not match driver output");
      ReleaseAsioResources();
      return Fail(
          kAsioDsdUnsupportedSampleType,
          "selected native DSD sample type does not match driver output");
    }

    query_result = ASIOGetLatencies(
        &constraints_.input_latency,
        &constraints_.output_latency);
    if (query_result != ASE_OK) {
      AddErrorEvent(query_result, "ASIOGetLatencies",
                    "ASIO native DSD latency query failed after buffer creation");
    }

    {
      std::lock_guard lock(stats_mutex_);
      stats_.expected_callback_interval_ms =
          1000.0 * static_cast<double>(constraints_.preferred_size) /
          static_cast<double>(config_.format.sample_rate_hz);
    }

    if (!TransitionTo(
            DeviceLifecycleState::kPrepared,
            "ASIO buffers created once for selected native DSD profile")) {
      ReleaseAsioResources();
      return OperationResult::Failure(kAsioDsdInvalidState,
                                      GetLastError().message);
    }
    AddPreparedEvent();
    return OperationResult::Success();
  }

  OperationResult StopAsioStream() {
    if (!started_) {
      return OperationResult::Success();
    }
    const ASIOError stop_result = ASIOStop();
    if (stop_result != ASE_OK) {
      AddErrorEvent(stop_result, "ASIOStop",
                    "failed to stop ASIO native DSD stream");
      return Fail(kAsioDsdStopFailed,
                  "failed to stop ASIO native DSD stream");
    }
    started_ = false;
    return OperationResult::Success();
  }

  OperationResult ReleaseAsioResources() {
    const auto stop = StopAsioStream();
    if (!stop.ok) {
      return stop;
    }
    SetActiveAsioNativeDsdCallbackSink(nullptr);

    if (buffers_created_) {
      const ASIOError dispose_result = ASIODisposeBuffers();
      if (dispose_result != ASE_OK) {
        AddErrorEvent(dispose_result, "ASIODisposeBuffers",
                      "failed to dispose ASIO native DSD buffers");
        return Fail(kAsioDsdDisposeFailed,
                    "failed to dispose ASIO native DSD buffers");
      }
      buffers_created_ = false;
      buffer_infos_.clear();
      channel_infos_.clear();
    }

    if (driver_loaded_) {
      const ASIOError exit_result = ASIOExit();
      if (exit_result != ASE_OK) {
        AddErrorEvent(exit_result, "ASIOExit",
                      "failed to release ASIO native DSD driver");
        return Fail(kAsioDsdExitFailed,
                    "failed to release ASIO native DSD driver");
      }
      driver_loaded_ = false;
      io_format_set_ = false;
    }
    return OperationResult::Success();
  }

  void OnAsioBufferSwitch(long buffer_index,
                          bool direct_process,
                          bool) override {
    FillOutputBuffer(buffer_index,
                     true,
                     direct_process,
                     policy_.uses_output_ready_if_supported);
  }

  void OnAsioSampleRateChanged(double sample_rate) override {
    DiagnosticEvent event;
    event.type = DiagnosticEventType::kRuntimeStats;
    event.sequence = NextSequence();
    event.backend = BackendApi::kAsio;
    event.device_id = config_.device.stable_id;
    event.message = "ASIO native DSD sampleRateDidChange callback";
    event.backend_fields["sample_rate_hz"] = std::to_string(sample_rate);
    event.backend_fields["driver_callback"] = "sampleRateDidChange";
    event.backend_fields["asio_io_format"] = "native-dsd";
    AppendEvent(std::move(event));
  }

  long OnAsioMessage(long selector, long value) override {
    DiagnosticEvent event;
    event.type = DiagnosticEventType::kRuntimeStats;
    event.sequence = NextSequence();
    event.backend = BackendApi::kAsio;
    event.device_id = config_.device.stable_id;
    event.message = "ASIO native DSD asioMessage callback";
    event.backend_fields["selector"] = std::to_string(selector);
    event.backend_fields["value"] = std::to_string(value);
    event.backend_fields["driver_callback"] = "asioMessage";
    event.backend_fields["asio_io_format"] = "native-dsd";

    long result = 0;
    switch (selector) {
      case kAsioSelectorSupported:
        result = value == kAsioResetRequest ||
                 value == kAsioEngineVersion ||
                 value == kAsioResyncRequest ||
                 value == kAsioLatenciesChanged ||
                 value == kAsioSupportsTimeInfo ||
                 value == kAsioOverload
                     ? 1
                     : 0;
        break;
      case kAsioEngineVersion:
        result = 2;
        break;
      case kAsioSupportsTimeInfo:
        result = 1;
        break;
      case kAsioResetRequest:
        event.backend_fields["reset_request_deferred"] = "true";
        {
          std::lock_guard lock(stats_mutex_);
          ++stats_.discontinuity_count;
        }
        result = 1;
        break;
      case kAsioResyncRequest:
        event.backend_fields["resync_request"] = "true";
        {
          std::lock_guard lock(stats_mutex_);
          ++stats_.discontinuity_count;
        }
        result = 1;
        break;
      case kAsioLatenciesChanged:
        event.backend_fields["latencies_changed"] = "true";
        result = 1;
        break;
      case kAsioOverload:
        event.backend_fields["overload"] = "true";
        {
          std::lock_guard lock(stats_mutex_);
          ++stats_.underrun_count;
        }
        result = 1;
        break;
      default:
        result = 0;
        break;
    }
    event.backend_fields["result"] = std::to_string(result);
    AppendEvent(std::move(event));
    return result;
  }

  bool FillOutputBuffer(long buffer_index,
                        bool count_stats,
                        bool direct_process,
                        bool allow_output_ready) {
    if (buffer_index < 0 || buffer_index > 1 ||
        buffer_bytes_per_channel_ == 0) {
      return false;
    }
    const auto before = std::chrono::steady_clock::now();
    for (auto& buffer : buffer_infos_) {
      if (buffer.buffers[buffer_index] == nullptr) {
        return false;
      }
    }

    const std::uint64_t written = signal_samples_written_.load();
    const bool idle_only = force_idle_ || written >= signal_sample_target_;
    NativeDsdGenerationResult generated;
    if (idle_only) {
      generated = generator_.GenerateIdle(dsd_config_, buffer_bytes_per_channel_);
    } else {
      NativeDsdSineConfig sine_config;
      sine_config.dsd = dsd_config_;
      sine_config.frequency_hz = config_.frequency_hz;
      sine_config.amplitude_dbfs = config_.amplitude_dbfs;
      generated = generator_.GenerateSine(sine_config, buffer_bytes_per_channel_);
    }
    if (!generated.ok ||
        generated.channel_payloads.size() != buffer_infos_.size()) {
      return false;
    }

    for (std::size_t channel = 0;
         channel < generated.channel_payloads.size();
         ++channel) {
      const auto& payload = generated.channel_payloads[channel];
      if (payload.size() < buffer_bytes_per_channel_) {
        return false;
      }
      std::memcpy(
          buffer_infos_[channel].buffers[buffer_index],
          payload.data(),
          buffer_bytes_per_channel_);
    }

    const auto samples_per_buffer = NativeDsdSamplesPerBuffer(
        buffer_bytes_per_channel_,
        config_.format.sample_type);
    if (!idle_only) {
      signal_samples_written_ += samples_per_buffer;
    }

    bool output_ready_called = false;
    if (allow_output_ready && constraints_.output_ready_supported) {
      output_ready_called = ASIOOutputReady() == ASE_OK;
    }

    if (count_stats) {
      {
        std::lock_guard lock(stats_mutex_);
        stats_.frames_generated += idle_only ? 0 : samples_per_buffer;
        stats_.frames_submitted += samples_per_buffer;
        stats_.frames_accepted += samples_per_buffer;
        ++stats_.callback_count;
        const auto now = std::chrono::steady_clock::now();
        const double interval_ms =
            std::chrono::duration<double, std::milli>(
                now - last_callback_time_).count();
        stats_.last_callback_interval_ms = interval_ms;
        stats_.max_callback_delay_ms =
            std::max(stats_.max_callback_delay_ms, interval_ms);
        last_callback_time_ = now;
      }
      const auto after = std::chrono::steady_clock::now();
      const double duration_ms =
          std::chrono::duration<double, std::milli>(after - before).count();
      AddRuntimeEvent(
          static_cast<std::int32_t>(buffer_index),
          duration_ms,
          direct_process,
          output_ready_called,
          idle_only);
    }

    if (GetState() == DeviceLifecycleState::kRunningSignal &&
        signal_samples_written_.load() >= signal_sample_target_) {
      if (policy_.keep_warm_after_signal) {
        force_idle_ = true;
        TransitionTo(
            DeviceLifecycleState::kRunningSilence,
            "signal ended; ASIO valid native DSD idle keep-warm is running");
      } else {
        TransitionTo(DeviceLifecycleState::kHeldOpen,
                     "signal ended; ASIO native DSD driver remains initialized");
      }
    }
    return true;
  }
#endif

  mutable std::mutex error_mutex_;
  mutable std::mutex state_mutex_;
  mutable std::mutex stats_mutex_;
  mutable std::mutex events_mutex_;
  BackendError last_error_;
  DeviceLifecycleState lifecycle_state_ = DeviceLifecycleState::kDiscovered;
  PlaybackConfig config_;
  NativeDsdConfig dsd_config_;
  AsioNativeDsdPolicy policy_;
  AsioNativeDsdConstraints constraints_;
  RealtimeStats stats_;
  std::vector<DiagnosticEvent> events_;
  std::uint64_t sequence_ = 0;
  std::atomic<std::uint64_t> signal_samples_written_{0};
  std::uint64_t signal_sample_target_ = 0;
  std::atomic<bool> force_idle_{false};
  NativeDsdSineGenerator generator_;
  std::chrono::steady_clock::time_point last_callback_time_ =
      std::chrono::steady_clock::now();
  std::optional<SampleType> asio_sample_type_;
  long output_channels_ = 0;
  double current_sample_rate_hz_ = 0.0;
  std::uint32_t buffer_bytes_per_channel_ = 0;
  std::string sample_rate_set_result_ = "not-queried";

#if APTT_ENABLE_ASIO && defined(_WIN32)
  ASIODriverInfo driver_info_{};
  ASIOCallbacks callbacks_{};
  std::vector<ASIOBufferInfo> buffer_infos_;
  std::vector<ASIOChannelInfo> channel_infos_;
  bool driver_loaded_ = false;
  bool buffers_created_ = false;
  bool started_ = false;
  bool io_format_set_ = false;
#endif
};

AsioNativeDsdBackend::AsioNativeDsdBackend()
    : impl_(std::make_unique<Impl>()) {}

AsioNativeDsdBackend::~AsioNativeDsdBackend() = default;

BackendApi AsioNativeDsdBackend::api() const {
  return impl_->Api();
}

DeviceList AsioNativeDsdBackend::enumerateDevices() {
  return impl_->EnumerateDevices();
}

FormatProbeResult AsioNativeDsdBackend::probeFormats(const DeviceInfo& device) {
  NativeDsdConfig requested_dsd;
  return impl_->ProbeFormats(device, requested_dsd);
}

FormatProbeResult AsioNativeDsdBackend::probeFormats(
    const DeviceInfo& device,
    const NativeDsdConfig& requested_dsd) {
  return impl_->ProbeFormats(device, requested_dsd);
}

OperationResult AsioNativeDsdBackend::initialize(const PlaybackConfig& config) {
  return impl_->Initialize(config);
}

OperationResult AsioNativeDsdBackend::start() {
  return impl_->Start();
}

OperationResult AsioNativeDsdBackend::stop() {
  return impl_->Stop();
}

OperationResult AsioNativeDsdBackend::reset() {
  return impl_->Reset();
}

RealtimeStats AsioNativeDsdBackend::getRealtimeStats() const {
  return impl_->GetRealtimeStats();
}

BackendError AsioNativeDsdBackend::getLastError() const {
  return impl_->GetLastError();
}

OperationResult AsioNativeDsdBackend::shutdown() {
  return impl_->Shutdown();
}

DeviceLifecycleState AsioNativeDsdBackend::lifecycle_state() const {
  return impl_->GetState();
}

std::vector<DiagnosticEvent> AsioNativeDsdBackend::diagnostic_events() const {
  return impl_->GetEvents();
}

}  // namespace aptt
