#include "backends/wasapi_shared_pcm_backend.h"

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

#include "backends/audio_thread_scheduling.h"
#include "backends/wasapi_endpoint_discovery.h"
#include "backends/wasapi_error.h"
#include "backends/wasapi_format_probe.h"
#include "core/high_load_diagnostics.h"
#include "core/pcm_sample_conversion.h"
#include "core/signal_generator.h"

#if defined(_WIN32)
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif
#ifndef NOMINMAX
#define NOMINMAX
#endif
#include <windows.h>
#include <audioclient.h>
#include <mmdeviceapi.h>
#include <mmreg.h>
#endif

namespace aptt {
namespace {

constexpr int kWasapiInvalidArgument = 0x70057;
constexpr int kWasapiNotInitialized = 0x20001;
constexpr int kWasapiInvalidState = 0x20002;
constexpr int kWasapiResetDisabled = 0x20003;
constexpr int kWasapiNotImplemented =
    static_cast<int>(static_cast<std::int32_t>(0x80004001u));
constexpr std::uint32_t kDefaultBufferDurationMs = 100;
constexpr std::uint32_t kDefaultRenderPollIntervalMs = 5;
constexpr std::uint64_t kHundredNsPerMs = 10000;

#if defined(_WIN32)

constexpr CLSID kClsidMmDeviceEnumerator = {
    0xbcde0395,
    0xe52f,
    0x467c,
    {0x8e, 0x3d, 0xc4, 0x57, 0x92, 0x91, 0x69, 0x2e},
};

constexpr GUID kWaveSubtypePcm = {
    0x00000001,
    0x0000,
    0x0010,
    {0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71},
};

constexpr GUID kWaveSubtypeIeeeFloat = {
    0x00000003,
    0x0000,
    0x0010,
    {0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71},
};

int HResultCode(HRESULT result) {
  return static_cast<int>(static_cast<std::int32_t>(result));
}

std::wstring Utf8ToWide(const std::string& value) {
  if (value.empty()) {
    return {};
  }
  const int required = MultiByteToWideChar(
      CP_UTF8, 0, value.c_str(), -1, nullptr, 0);
  if (required <= 1) {
    return {};
  }
  std::wstring converted(static_cast<std::size_t>(required - 1), L'\0');
  MultiByteToWideChar(
      CP_UTF8, 0, value.c_str(), -1, converted.data(), required);
  return converted;
}

template <typename T>
void SafeRelease(T*& ptr) {
  if (ptr != nullptr) {
    ptr->Release();
    ptr = nullptr;
  }
}

WAVEFORMATEXTENSIBLE WaveFormatFromDescriptor(const FormatDescriptor& descriptor) {
  WAVEFORMATEXTENSIBLE wave{};
  wave.Format.wFormatTag = WAVE_FORMAT_EXTENSIBLE;
  wave.Format.nChannels = static_cast<WORD>(descriptor.channels.channel_count);
  wave.Format.nSamplesPerSec = descriptor.sample_rate_hz;
  wave.Format.wBitsPerSample =
      static_cast<WORD>(descriptor.container_bits_per_sample);
  wave.Format.nBlockAlign =
      static_cast<WORD>((wave.Format.nChannels * wave.Format.wBitsPerSample) / 8);
  wave.Format.nAvgBytesPerSec =
      wave.Format.nSamplesPerSec * wave.Format.nBlockAlign;
  wave.Format.cbSize = sizeof(WAVEFORMATEXTENSIBLE) - sizeof(WAVEFORMATEX);
  wave.Samples.wValidBitsPerSample =
      static_cast<WORD>(descriptor.valid_bits_per_sample);
  wave.dwChannelMask = descriptor.channels.channel_mask;
  wave.SubFormat = descriptor.sample_type == SampleType::kFloat32
                       ? kWaveSubtypeIeeeFloat
                       : kWaveSubtypePcm;
  return wave;
}

class ScopedThreadCom {
 public:
  ScopedThreadCom() {
    result_ = CoInitializeEx(nullptr, COINIT_MULTITHREADED);
    if (result_ == S_OK || result_ == S_FALSE) {
      needs_uninitialize_ = true;
    } else if (result_ == RPC_E_CHANGED_MODE) {
      result_ = S_OK;
    }
  }

  ScopedThreadCom(const ScopedThreadCom&) = delete;
  ScopedThreadCom& operator=(const ScopedThreadCom&) = delete;

  ~ScopedThreadCom() {
    if (needs_uninitialize_) {
      CoUninitialize();
    }
  }

  HRESULT result() const { return result_; }

 private:
  HRESULT result_ = E_FAIL;
  bool needs_uninitialize_ = false;
};

#endif

bool IsDeviceInvalidatedResult(int code) {
#if defined(_WIN32)
  return code == HResultCode(AUDCLNT_E_DEVICE_INVALIDATED) ||
         code == HResultCode(AUDCLNT_E_RESOURCES_INVALIDATED) ||
         code == HResultCode(AUDCLNT_E_SERVICE_NOT_RUNNING);
#else
  (void)code;
  return false;
#endif
}

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

OperationResult ValidateConfigForPlayback(const PlaybackConfig& config) {
  if (config.backend != BackendApi::kWasapiShared) {
    return OperationResult::Failure(
        kWasapiInvalidArgument,
        "WASAPI shared PCM playback requires BackendApi::kWasapiShared");
  }
  if (config.device.stable_id.empty()) {
    return OperationResult::Failure(
        kWasapiInvalidArgument,
        "WASAPI shared PCM playback requires an explicit endpoint ID");
  }
  if (config.format.signal_mode != SignalMode::kPcm) {
    return OperationResult::Failure(
        kWasapiInvalidArgument,
        "WASAPI shared playback slice supports PCM only");
  }
  if (!IsWasapiSharedPcmPlaybackFormat(config.format)) {
    return OperationResult::Failure(
        kWasapiInvalidArgument,
        "WASAPI shared playback requires a renderable PCM format");
  }
  if (config.format.sample_rate_hz == 0 ||
      config.format.channels.channel_count == 0) {
    return OperationResult::Failure(
        kWasapiInvalidArgument,
        "WASAPI shared PCM playback requires a non-zero sample rate and channel count");
  }
  return OperationResult::Success();
}

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;
  return summary.str();
}

}  // namespace

WasapiSharedPcmPolicy MakeWasapiSharedPcmPolicy(const PlaybackConfig& config) {
  WasapiSharedPcmPolicy policy;
  policy.keep_warm_after_signal = config.hold_mode == HoldMode::kKeepWarmAfterStop;
  policy.release_after_drain = config.hold_mode == HoldMode::kReleaseAfterDrain;
  policy.buffer_duration_ms =
      std::max<std::uint32_t>(1, config.wasapi_shared_buffer_duration_ms);
  policy.render_poll_interval_ms =
      std::max<std::uint32_t>(1, config.wasapi_shared_render_poll_interval_ms);
  policy.release_cooldown_ms = config.release_cooldown_ms == 0
                                   ? 1
                                   : config.release_cooldown_ms;
  return policy;
}

bool IsWasapiSharedPcmPlaybackFormat(const FormatDescriptor& format) {
  return IsRenderablePcmFormat(format);
}

struct WasapiSharedPcmBackend::Impl {
  ~Impl() { Shutdown(); }

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

  DeviceList EnumerateDevices() {
    DeviceList devices;
    const auto snapshot = EnumerateWasapiRenderEndpoints();
    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) {
    FormatProbeResult result;
    result.requested = WasapiDefaultPcmCandidate();
    if (device.stable_id.empty()) {
      result.rejection_reasons.push_back(
          "WASAPI shared format probe requires an explicit endpoint ID");
      return result;
    }

    WasapiFormatProbeRequest request;
    request.endpoint_id = device.stable_id;
    request.exclusive_mode = false;
    request.candidate_formats = WasapiDefaultPcmCandidates();

    const auto snapshot = ProbeWasapiEndpointFormats(request);
    for (const auto& probe : snapshot.probes) {
      if (probe.accepted_format) {
        result.supported_formats.push_back(*probe.accepted_format);
      }
      if (probe.error) {
        result.rejection_reasons.push_back(probe.error->message);
      }
    }
    return result;
  }

  OperationResult Initialize(const PlaybackConfig& config) {
    auto validation = ValidateConfigForPlayback(config);
    if (!validation.ok) {
      SetLastError(validation.error);
      return validation;
    }

    Shutdown();

    {
      std::scoped_lock lock(state_mutex_, stats_mutex_, events_mutex_);
      config_ = config;
      policy_ = MakeWasapiSharedPcmPolicy(config_);
      stats_ = {};
      events_.clear();
      sequence_ = 0;
      state_ = DeviceLifecycleState::kDiscovered;
      signal_frame_target_ = DurationFrames(config_);
      signal_frames_written_ = 0;
      force_silence_ = false;
      last_error_ = {};
      generator_.ResetPhase();
    }

    if (!TransitionTo(DeviceLifecycleState::kReserved, "selected WASAPI endpoint reserved")) {
      return OperationResult::Failure(kWasapiInvalidState, GetLastError().message);
    }

#if !defined(_WIN32)
    TransitionTo(DeviceLifecycleState::kFaulted, "WASAPI shared playback is not available");
    return Fail(
        kWasapiNotImplemented,
        "WASAPI shared playback is available only on Windows");
#else
    HRESULT result = InitializeComIfNeeded();
    if (FAILED(result)) {
      TransitionTo(DeviceLifecycleState::kFaulted, "COM initialization failed");
      return Fail(
          HResultCode(result),
          "failed to initialize COM for WASAPI shared playback");
    }

    result = CoCreateInstance(
        kClsidMmDeviceEnumerator,
        nullptr,
        CLSCTX_ALL,
        IID_PPV_ARGS(&enumerator_));
    if (FAILED(result) || enumerator_ == nullptr) {
      TransitionTo(DeviceLifecycleState::kFaulted, "MMDeviceEnumerator creation failed");
      ReleaseInterfaces();
      return Fail(
          HResultCode(result),
          "failed to create MMDeviceEnumerator for WASAPI shared playback");
    }

    const std::wstring endpoint_id = Utf8ToWide(config_.device.stable_id);
    result = enumerator_->GetDevice(endpoint_id.c_str(), &endpoint_);
    if (FAILED(result) || endpoint_ == nullptr) {
      TransitionTo(DeviceLifecycleState::kFaulted, "selected endpoint open failed");
      ReleaseInterfaces();
      return Fail(
          HResultCode(result),
          "failed to open selected WASAPI endpoint by ID");
    }

    result = endpoint_->Activate(
        __uuidof(IAudioClient),
        CLSCTX_ALL,
        nullptr,
        reinterpret_cast<void**>(&audio_client_));
    if (FAILED(result) || audio_client_ == nullptr) {
      TransitionTo(DeviceLifecycleState::kFaulted, "IAudioClient activation failed");
      ReleaseInterfaces();
      return Fail(
          HResultCode(result),
          "failed to activate IAudioClient for WASAPI shared playback");
    }

    wave_format_ = WaveFormatFromDescriptor(config_.format);
    const REFERENCE_TIME requested_buffer_duration =
        static_cast<REFERENCE_TIME>(
            static_cast<std::uint64_t>(policy_.buffer_duration_ms) *
            kHundredNsPerMs);
    result = audio_client_->Initialize(
        AUDCLNT_SHAREMODE_SHARED,
        0,
        requested_buffer_duration,
        0,
        &wave_format_.Format,
        nullptr);
    if (FAILED(result)) {
      const int code = HResultCode(result);
      const std::string message = DescribeWasapiAudioClientError(
          code,
          "IAudioClient::Initialize",
          "failed to initialize WASAPI shared stream");
      AddErrorEvent(code, "IAudioClient::Initialize", message);
      TransitionTo(DeviceLifecycleState::kFaulted,
                   std::string("IAudioClient::Initialize failed: ") +
                       WasapiAudioClientErrorSymbol(code));
      ReleaseInterfaces();
      return Fail(code, message);
    }

    result = audio_client_->GetBufferSize(&buffer_frames_);
    if (FAILED(result) || buffer_frames_ == 0) {
      TransitionTo(DeviceLifecycleState::kFaulted, "IAudioClient::GetBufferSize failed");
      ReleaseInterfaces();
      return Fail(
          HResultCode(result),
          "failed to query WASAPI shared buffer size");
    }

    result = audio_client_->GetService(
        __uuidof(IAudioRenderClient),
        reinterpret_cast<void**>(&render_client_));
    if (FAILED(result) || render_client_ == nullptr) {
      TransitionTo(DeviceLifecycleState::kFaulted, "IAudioRenderClient service failed");
      ReleaseInterfaces();
      return Fail(
          HResultCode(result),
          "failed to acquire IAudioRenderClient");
    }

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

    if (!TransitionTo(DeviceLifecycleState::kPrepared,
                      "WASAPI shared stream initialized once")) {
      ReleaseInterfaces();
      return OperationResult::Failure(kWasapiInvalidState, GetLastError().message);
    }
    AddInitializationEvent(requested_buffer_duration);
    return OperationResult::Success();
#endif
  }

  OperationResult Start() {
#if !defined(_WIN32)
    return Fail(kWasapiNotImplemented, "WASAPI shared playback is available only on Windows");
#else
    const auto current = GetState();
    if (current == DeviceLifecycleState::kRunningSilence && render_thread_.joinable()) {
      return Fail(
          kWasapiInvalidState,
          "WASAPI shared RunningSilence restart requires explicit release before rerun");
    }
    if (current != DeviceLifecycleState::kPrepared &&
        current != DeviceLifecycleState::kHeldOpen) {
      return Fail(kWasapiInvalidState, "WASAPI shared stream must be prepared before start");
    }
    if (audio_client_ == nullptr || render_client_ == nullptr) {
      return Fail(kWasapiNotInitialized, "WASAPI shared stream is not initialized");
    }

    force_silence_ = false;
    render_thread_stop_ = false;
    signal_frames_written_ = 0;
    generator_.ResetPhase();
    last_callback_time_ = std::chrono::steady_clock::now();

    if (!TransitionTo(DeviceLifecycleState::kRunningSignal,
                      "WASAPI shared 1 kHz signal started")) {
      return OperationResult::Failure(kWasapiInvalidState, GetLastError().message);
    }

    if (!FillRenderBuffer(buffer_frames_)) {
      TransitionTo(DeviceLifecycleState::kFaulted, "initial WASAPI render fill failed");
      return OperationResult::Failure(kWasapiInvalidState, GetLastError().message);
    }

    const HRESULT result = audio_client_->Start();
    if (FAILED(result)) {
      TransitionTo(DeviceLifecycleState::kFaulted, "IAudioClient::Start failed");
      return Fail(HResultCode(result), "failed to start WASAPI shared stream");
    }

    render_thread_ = std::thread([this] { RenderLoop(); });
    return OperationResult::Success();
#endif
  }

  OperationResult Stop() {
    const auto current = GetState();
    if (current == DeviceLifecycleState::kRunningSignal &&
        policy_.keep_warm_after_signal) {
      force_silence_ = true;
      if (!TransitionTo(DeviceLifecycleState::kRunningSilence,
                        "normal stop switched to valid PCM silence keep-warm")) {
        return OperationResult::Failure(kWasapiInvalidState, GetLastError().message);
      }
      return OperationResult::Success();
    }
    if (current == DeviceLifecycleState::kRunningSilence &&
        policy_.keep_warm_after_signal) {
      return OperationResult::Success();
    }

    if (current == DeviceLifecycleState::kRunningSignal ||
        current == DeviceLifecycleState::kRunningSilence) {
      if (!TransitionTo(DeviceLifecycleState::kDraining,
                        "WASAPI shared stream draining before stop")) {
        return OperationResult::Failure(kWasapiInvalidState, GetLastError().message);
      }
      StopRenderThread();
#if defined(_WIN32)
      if (audio_client_ != nullptr) {
        const HRESULT result = audio_client_->Stop();
        if (FAILED(result)) {
          TransitionTo(DeviceLifecycleState::kFaulted, "IAudioClient::Stop failed");
          return Fail(HResultCode(result), "failed to stop WASAPI shared stream");
        }
      }
#endif
    }

    if (policy_.release_after_drain) {
      return ReleaseAfterDrain();
    }

    if (GetState() != DeviceLifecycleState::kHeldOpen) {
      if (!TransitionTo(DeviceLifecycleState::kHeldOpen,
                        "WASAPI shared stream held initialized after stop")) {
        return OperationResult::Failure(kWasapiInvalidState, GetLastError().message);
      }
    }
    return OperationResult::Success();
  }

  OperationResult Reset() {
    return Fail(
        kWasapiResetDisabled,
        "WASAPI shared normal reset is disabled; use drain/keep-warm/release lifecycle");
  }

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

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

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

    if (current == DeviceLifecycleState::kRunningSignal ||
        current == DeviceLifecycleState::kRunningSilence) {
      if (!TransitionTo(DeviceLifecycleState::kDraining,
                        "WASAPI shared stream draining before release")) {
        return OperationResult::Failure(kWasapiInvalidState, GetLastError().message);
      }
    }

    StopRenderThread();
#if defined(_WIN32)
    if (audio_client_ != nullptr) {
      const HRESULT result = audio_client_->Stop();
      if (FAILED(result) && !IsDeviceInvalidatedResult(HResultCode(result))) {
        TransitionTo(DeviceLifecycleState::kFaulted, "IAudioClient::Stop failed during shutdown");
        ReleaseInterfaces();
        return Fail(HResultCode(result), "failed to stop WASAPI shared stream during shutdown");
      }
    }
#endif

    return ReleaseAfterDrain();
  }

  DeviceLifecycleState GetState() const {
    std::lock_guard lock(state_mutex_);
    return 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 = 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({kWasapiInvalidState, decision.reason});
        return false;
      }
      state_ = next;
    }

    auto event = MakeLifecycleEvent(
        NextSequence(),
        BackendApi::kWasapiShared,
        config_.device.stable_id,
        previous,
        next,
        std::move(message));
    event.backend_fields["hold_mode"] = ToString(config_.hold_mode);
    event.backend_fields["reset_used"] = "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 AddInitializationEvent(std::int64_t requested_buffer_duration_100ns) {
    DiagnosticEvent event;
    event.type = DiagnosticEventType::kFormatProbe;
    event.sequence = NextSequence();
    event.backend = BackendApi::kWasapiShared;
    event.device_id = config_.device.stable_id;
    event.format = config_.format;
    event.message = "WASAPI shared PCM stream initialized";
    event.backend_fields["requested_format"] = FormatSummary(config_.format);
    event.backend_fields["accepted_format"] = FormatSummary(config_.format);
    event.backend_fields["share_mode"] = "shared";
    event.backend_fields["fallback_endpoint"] = "false";
    event.backend_fields["fallback_format"] = "false";
    event.backend_fields["requested_buffer_duration_100ns"] =
        std::to_string(requested_buffer_duration_100ns);
    event.backend_fields["buffer_frames"] = std::to_string(buffer_frames_);
    event.backend_fields["render_poll_interval_ms"] =
        std::to_string(policy_.render_poll_interval_ms);
    event.backend_fields["audio_thread_mmcss_enabled"] =
        config_.audio_thread_mmcss_enabled ? "true" : "false";
    event.backend_fields["audio_thread_mmcss_task_name"] =
        config_.audio_thread_mmcss_task_name;
    event.backend_fields["audio_thread_mmcss_priority"] =
        std::to_string(config_.audio_thread_mmcss_priority);
    AddHighLoadDiagnosticFields(config_, event.backend_fields);
    AppendEvent(std::move(event));
  }

  void AddThreadSchedulingEvent(
      const AudioThreadMmcssRegistrationSnapshot& snapshot,
      std::string message) {
    DiagnosticEvent event;
    event.type = DiagnosticEventType::kRuntimeStats;
    event.sequence = NextSequence();
    event.backend = BackendApi::kWasapiShared;
    event.device_id = config_.device.stable_id;
    event.message = std::move(message);
    event.backend_fields["api"] = "AvSetMmThreadCharacteristics";
    event.backend_fields["thread_role"] = "WASAPI shared render thread";
    AddAudioThreadMmcssBackendFields(event.backend_fields, snapshot);
    AppendEvent(std::move(event));
  }

  void AddRuntimeEvent(std::uint32_t padding_frames,
                       std::uint32_t available_frames,
                       std::uint32_t submitted_frames) {
    const auto stats = GetRealtimeStats();
    if (stats.callback_count > 8 && (stats.callback_count % 50) != 0) {
      return;
    }

    DiagnosticEvent event;
    event.type = DiagnosticEventType::kRuntimeStats;
    event.sequence = NextSequence();
    event.backend = BackendApi::kWasapiShared;
    event.device_id = config_.device.stable_id;
    event.message = "WASAPI shared buffer update";
    event.realtime_stats = stats;
    event.backend_fields["buffer_frames"] = std::to_string(buffer_frames_);
    event.backend_fields["padding_frames"] = std::to_string(padding_frames);
    event.backend_fields["available_frames"] = std::to_string(available_frames);
    event.backend_fields["submitted_frames"] = std::to_string(submitted_frames);
    AddHighLoadDiagnosticFields(config_, event.backend_fields);
    if (HighLoadLateCallbackJustOccurred(config_, stats)) {
      event.backend_fields["late_callback"] = "true";
      event.backend_fields["late_callback_source"] =
          "high_load_render_delay";
    }
    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::kWasapiShared;
    event.device_id = config_.device.stable_id;
    event.message = message;
    event.backend_fields["api"] = std::move(api);
    event.backend_fields["code"] = std::to_string(code);
    event.backend_fields["symbol"] = WasapiAudioClientErrorSymbol(code);
    event.backend_fields["device_invalidated"] =
        IsDeviceInvalidatedResult(code) ? "true" : "false";
    AppendEvent(std::move(event));
  }

#if defined(_WIN32)
  HRESULT InitializeComIfNeeded() {
    if (com_ready_) {
      return S_OK;
    }
    const HRESULT result = CoInitializeEx(nullptr, COINIT_MULTITHREADED);
    if (result == S_OK || result == S_FALSE) {
      com_ready_ = true;
      com_needs_uninitialize_ = true;
      return S_OK;
    }
    if (result == RPC_E_CHANGED_MODE) {
      com_ready_ = true;
      com_needs_uninitialize_ = false;
      return S_OK;
    }
    return result;
  }

  void ReleaseInterfaces() {
    SafeRelease(render_client_);
    SafeRelease(audio_client_);
    SafeRelease(endpoint_);
    SafeRelease(enumerator_);
    buffer_frames_ = 0;
    if (com_needs_uninitialize_) {
      CoUninitialize();
    }
    com_ready_ = false;
    com_needs_uninitialize_ = false;
  }
#else
  void ReleaseInterfaces() {}
#endif

  OperationResult ReleaseAfterDrain() {
    const auto current = GetState();
    if (current == DeviceLifecycleState::kFaulted) {
      StopRenderThread();
      ReleaseInterfaces();
      if (!TransitionTo(DeviceLifecycleState::kReleased,
                        "faulted WASAPI shared resources released once")) {
        return OperationResult::Failure(kWasapiInvalidState, GetLastError().message);
      }
      return OperationResult::Success();
    }

    if (current != DeviceLifecycleState::kReleasing &&
        current != DeviceLifecycleState::kReleased) {
      if (!TransitionTo(DeviceLifecycleState::kReleasing,
                        "WASAPI shared resources releasing after drain")) {
        return OperationResult::Failure(kWasapiInvalidState, GetLastError().message);
      }
    }

    if (policy_.release_cooldown_ms > 0) {
      std::this_thread::sleep_for(
          std::chrono::milliseconds(policy_.release_cooldown_ms));
    }
    ReleaseInterfaces();
    if (!TransitionTo(DeviceLifecycleState::kReleased,
                      "WASAPI shared resources released once")) {
      return OperationResult::Failure(kWasapiInvalidState, GetLastError().message);
    }
    return OperationResult::Success();
  }

  void StopRenderThread() {
    render_thread_stop_ = true;
    if (render_thread_.joinable()) {
      render_thread_.join();
    }
  }

#if defined(_WIN32)
  bool FillRenderBuffer(std::uint32_t frames) {
    if (frames == 0) {
      return true;
    }
    BYTE* raw_buffer = nullptr;
    HRESULT result = render_client_->GetBuffer(frames, &raw_buffer);
    if (FAILED(result) || raw_buffer == nullptr) {
      const int code = HResultCode(result);
      AddErrorEvent(code, "IAudioRenderClient::GetBuffer",
                    "failed to acquire WASAPI render buffer");
      SetLastError({code, "failed to acquire WASAPI render buffer"});
      return false;
    }

    const std::uint64_t written = signal_frames_written_.load();
    const bool silence_only = force_silence_ || written >= signal_frame_target_;
    const std::uint32_t signal_frames = silence_only
        ? 0
        : static_cast<std::uint32_t>(std::min<std::uint64_t>(
              frames,
              signal_frame_target_ - written));

    if (signal_frames == 0) {
      result = render_client_->ReleaseBuffer(frames, AUDCLNT_BUFFERFLAGS_SILENT);
    } else {
      if (!WriteSignalAndSilence(raw_buffer, frames, signal_frames)) {
        render_client_->ReleaseBuffer(frames, AUDCLNT_BUFFERFLAGS_SILENT);
        return false;
      }
      result = render_client_->ReleaseBuffer(frames, 0);
      signal_frames_written_ += signal_frames;
    }

    if (FAILED(result)) {
      const int code = HResultCode(result);
      AddErrorEvent(code, "IAudioRenderClient::ReleaseBuffer",
                    "failed to release WASAPI render buffer");
      SetLastError({code, "failed to release WASAPI render buffer"});
      return false;
    }

    {
      std::lock_guard lock(stats_mutex_);
      stats_.frames_generated += signal_frames;
      stats_.frames_submitted += frames;
      stats_.frames_accepted += frames;
      ++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);
      CountHighLoadLateCallbackIfNeeded(config_, stats_);
      last_callback_time_ = now;
    }

    if (GetState() == DeviceLifecycleState::kRunningSignal &&
        (force_silence_ || signal_frames_written_.load() >= signal_frame_target_)) {
      if (policy_.keep_warm_after_signal) {
        TransitionTo(DeviceLifecycleState::kRunningSilence,
                     "signal ended; valid PCM silence keep-warm is running");
      } else {
        TransitionTo(DeviceLifecycleState::kHeldOpen,
                     "signal ended; stream remains initialized");
        render_thread_stop_ = true;
      }
    }
    return true;
  }

  bool WriteSignalAndSilence(BYTE* raw_buffer,
                             std::uint32_t total_frames,
                             std::uint32_t signal_frames) {
    const auto& format = config_.format;
    const std::uint32_t channels = format.channels.channel_count;
    const std::size_t total_bytes =
        static_cast<std::size_t>(total_frames) * wave_format_.Format.nBlockAlign;
    std::memset(raw_buffer, 0, total_bytes);

    PcmSineConfig sine_config;
    sine_config.sample_rate_hz = format.sample_rate_hz;
    sine_config.channel_count = channels;
    sine_config.frequency_hz = config_.frequency_hz;
    sine_config.amplitude_dbfs = config_.amplitude_dbfs;
    if (config_.left_channel_enabled && !config_.right_channel_enabled) {
      sine_config.channel_assignment = ChannelAssignment::kLeftOnly;
    } else if (!config_.left_channel_enabled && config_.right_channel_enabled) {
      sine_config.channel_assignment = ChannelAssignment::kRightOnly;
    }
    sine_config.invert_right = config_.invert_right_phase;
    sine_config.right_channel_phase_offset_degrees =
        config_.right_channel_phase_offset_degrees;
    const auto samples =
        generator_.GenerateInterleavedFloat32(sine_config, signal_frames);

    if (format.sample_type == SampleType::kFloat32) {
      const auto bytes = ConvertFloat32InterleavedToPcmBytes(
          samples,
          channels,
          format);
      if (bytes.empty()) {
        AddErrorEvent(kWasapiInvalidArgument,
                      "ConvertFloat32InterleavedToPcmBytes",
                      "failed to convert WASAPI shared PCM buffer");
        SetLastError({kWasapiInvalidArgument,
                      "failed to convert WASAPI shared PCM buffer"});
        force_silence_ = true;
        return false;
      }
      std::memcpy(raw_buffer, bytes.data(), bytes.size());
      return true;
    }

    const auto bytes = ConvertFloat32InterleavedToPcmBytes(
        samples,
        channels,
        format);
    if (bytes.empty()) {
      AddErrorEvent(kWasapiInvalidArgument,
                    "ConvertFloat32InterleavedToPcmBytes",
                    "failed to convert WASAPI shared PCM buffer");
      SetLastError({kWasapiInvalidArgument,
                    "failed to convert WASAPI shared PCM buffer"});
      force_silence_ = true;
      return false;
    }
    std::memcpy(raw_buffer, bytes.data(), bytes.size());
    return true;
  }

  void RenderLoop() {
    ScopedThreadCom com;
    if (FAILED(com.result())) {
      const int code = HResultCode(com.result());
      AddErrorEvent(code, "CoInitializeEx",
                    "failed to initialize COM on WASAPI render thread");
      TransitionTo(DeviceLifecycleState::kFaulted,
                   "WASAPI render thread COM initialization failed");
      return;
    }
    ScopedAudioThreadMmcssRegistration mmcss({
        config_.audio_thread_mmcss_enabled,
        config_.audio_thread_mmcss_task_name,
        config_.audio_thread_mmcss_priority,
    });
    AddThreadSchedulingEvent(
        mmcss.snapshot(),
        "WASAPI shared render thread MMCSS registration evaluated");

    while (!render_thread_stop_) {
      std::uint32_t padding_frames = 0;
      const HRESULT padding_result = audio_client_->GetCurrentPadding(&padding_frames);
      if (FAILED(padding_result)) {
        const int code = HResultCode(padding_result);
        {
          std::lock_guard lock(stats_mutex_);
          if (IsDeviceInvalidatedResult(code)) {
            ++stats_.device_invalidated_count;
          } else {
            ++stats_.discontinuity_count;
          }
        }
        AddErrorEvent(code, "IAudioClient::GetCurrentPadding",
                      "failed to query WASAPI shared padding");
        TransitionTo(DeviceLifecycleState::kFaulted,
                     IsDeviceInvalidatedResult(code)
                         ? "WASAPI endpoint invalidated during shared playback"
                         : "WASAPI shared padding query failed");
        render_thread_stop_ = true;
        break;
      }

      const std::uint32_t available_frames =
          buffer_frames_ > padding_frames ? buffer_frames_ - padding_frames : 0;
      if (available_frames > 0) {
        ApplyHighLoadRenderDelay(config_, GetRealtimeStats().callback_count);
        if (!FillRenderBuffer(available_frames)) {
          const auto error = GetLastError();
          {
            std::lock_guard lock(stats_mutex_);
            if (IsDeviceInvalidatedResult(error.code)) {
              ++stats_.device_invalidated_count;
            } else {
              ++stats_.discontinuity_count;
            }
          }
          TransitionTo(DeviceLifecycleState::kFaulted,
                       "WASAPI shared render write failed");
          render_thread_stop_ = true;
          break;
        }
      }
      AddRuntimeEvent(padding_frames, available_frames, available_frames);
      std::this_thread::sleep_for(
          std::chrono::milliseconds(policy_.render_poll_interval_ms));
    }
    AddThreadSchedulingEvent(
        mmcss.Revert(),
        "WASAPI shared render thread MMCSS registration reverted");
  }
#endif

  mutable std::mutex state_mutex_;
  mutable std::mutex stats_mutex_;
  mutable std::mutex error_mutex_;
  mutable std::mutex events_mutex_;
  PlaybackConfig config_;
  WasapiSharedPcmPolicy policy_;
  RealtimeStats stats_;
  BackendError last_error_;
  std::vector<DiagnosticEvent> events_;
  std::atomic<std::uint64_t> sequence_{0};
  DeviceLifecycleState state_ = DeviceLifecycleState::kDiscovered;
  PcmSineGenerator generator_;
  std::uint64_t signal_frame_target_ = 0;
  std::atomic<std::uint64_t> signal_frames_written_{0};
  std::atomic<bool> render_thread_stop_{false};
  std::atomic<bool> force_silence_{false};
  std::thread render_thread_;
  std::chrono::steady_clock::time_point last_callback_time_ =
      std::chrono::steady_clock::now();

#if defined(_WIN32)
  bool com_ready_ = false;
  bool com_needs_uninitialize_ = false;
  IMMDeviceEnumerator* enumerator_ = nullptr;
  IMMDevice* endpoint_ = nullptr;
  IAudioClient* audio_client_ = nullptr;
  IAudioRenderClient* render_client_ = nullptr;
  WAVEFORMATEXTENSIBLE wave_format_{};
  std::uint32_t buffer_frames_ = 0;
#endif
};

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

WasapiSharedPcmBackend::~WasapiSharedPcmBackend() = default;

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

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

FormatProbeResult WasapiSharedPcmBackend::probeFormats(const DeviceInfo& device) {
  return impl_->ProbeFormats(device);
}

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

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

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

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

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

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

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

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

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

}  // namespace aptt
