#include <cstdlib>
#include <iostream>
#include <string_view>

#include "backends/null_backend.h"

namespace {

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

void TestNullBackendEnumeratesSyntheticDevice() {
  aptt::NullBackend backend;
  const auto devices = backend.enumerateDevices();
  Expect(devices.size() == 1, "NullBackend exposes one synthetic device");
  Expect(devices.front().backend == aptt::BackendApi::kNull,
         "synthetic device uses Null backend");
  Expect(devices.front().stable_id == "null-device", "synthetic stable ID");
}

void TestNullBackendRunUpdatesStatsAndKeepsWarm() {
  aptt::NullBackend backend;
  aptt::PlaybackConfig config;
  config.duration_ms = 100;
  config.format.sample_rate_hz = 48000;
  config.format.channels.channel_count = 2;
  config.hold_mode = aptt::HoldMode::kKeepWarmAfterStop;

  Expect(backend.initialize(config).ok, "initialize succeeds");
  Expect(backend.lifecycle_state() == aptt::DeviceLifecycleState::kPrepared,
         "initialized state is prepared");
  Expect(backend.start().ok, "start succeeds");

  const auto stats = backend.getRealtimeStats();
  Expect(stats.frames_generated == 4800, "generated expected frame count");
  Expect(stats.frames_submitted == 4800, "submitted expected frame count");
  Expect(stats.frames_accepted == 4800, "accepted expected frame count");
  Expect(stats.callback_count > 0, "callback count simulated");
  Expect(stats.underrun_count == 0, "NullBackend has no underruns");
  Expect(backend.lifecycle_state() == aptt::DeviceLifecycleState::kRunningSilence,
         "keep-warm state is running silence");

  Expect(backend.stop().ok, "stop succeeds");
  Expect(backend.lifecycle_state() == aptt::DeviceLifecycleState::kHeldOpen,
         "stop drains into held-open state");
  Expect(backend.shutdown().ok, "shutdown succeeds");
  Expect(backend.lifecycle_state() == aptt::DeviceLifecycleState::kReleased,
         "shutdown releases synthetic backend");
}

}  // namespace

int main() {
  TestNullBackendEnumeratesSyntheticDevice();
  TestNullBackendRunUpdatesStatsAndKeepsWarm();

  std::cout << "null backend tests passed\n";
  return 0;
}

