#pragma once

#include <cstdint>
#include <memory>
#include <string>
#include <vector>

#include "core/audio_backend.h"
#include "core/diagnostic_log.h"
#include "core/native_dsd_generator.h"

namespace aptt {

struct AsioNativeDsdPolicy {
  bool requires_explicit_driver = true;
  bool keep_warm_after_signal = true;
  bool release_after_drain = false;
  bool opens_control_panel = false;
  bool uses_repeated_asio_exit = false;
  bool uses_valid_dsd_idle = true;
  bool uses_output_ready_if_supported = true;
  std::uint32_t release_cooldown_ms = 1000;
};

AsioNativeDsdPolicy MakeAsioNativeDsdPolicy(const PlaybackConfig& config);
bool IsAsioNativeDsdPlaybackFormat(const FormatDescriptor& format);

DiagnosticEvent MakeAsioNativeDsdPreparedEvent(
    std::uint64_t sequence,
    std::string device_id,
    const FormatDescriptor& format,
    std::uint32_t buffer_bytes_per_channel);

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);

class AsioNativeDsdBackend final : public IAudioBackend {
 public:
  AsioNativeDsdBackend();
  ~AsioNativeDsdBackend() override;

  BackendApi api() const override;
  DeviceList enumerateDevices() override;
  FormatProbeResult probeFormats(const DeviceInfo& device) override;
  FormatProbeResult probeFormats(const DeviceInfo& device,
                                 const NativeDsdConfig& requested_dsd);
  OperationResult initialize(const PlaybackConfig& config) override;
  OperationResult start() override;
  OperationResult stop() override;
  OperationResult reset() override;
  RealtimeStats getRealtimeStats() const override;
  BackendError getLastError() const override;
  OperationResult shutdown() override;

  DeviceLifecycleState lifecycle_state() const;
  std::vector<DiagnosticEvent> diagnostic_events() const;

 private:
  struct Impl;
  std::unique_ptr<Impl> impl_;
};

}  // namespace aptt
