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

#include "backends/audio_thread_scheduling.h"

namespace {

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

void TestPriorityLabelsClampToSupportedRange() {
  Expect(aptt::AudioThreadMmcssPriorityLabel(-2) == "Low",
         "priority below low clamps to Low");
  Expect(aptt::AudioThreadMmcssPriorityLabel(-1) == "Low",
         "low priority label");
  Expect(aptt::AudioThreadMmcssPriorityLabel(0) == "Normal",
         "normal priority label");
  Expect(aptt::AudioThreadMmcssPriorityLabel(1) == "High",
         "high priority label");
  Expect(aptt::AudioThreadMmcssPriorityLabel(2) == "Critical",
         "critical priority label");
  Expect(aptt::AudioThreadMmcssPriorityLabel(3) == "Critical",
         "priority above critical clamps to Critical");
}

void TestDisabledRegistrationDoesNotTouchMmcss() {
  aptt::ScopedAudioThreadMmcssRegistration registration(
      {false, "not-a-real-task", 99});
  const auto snapshot = registration.snapshot();

  Expect(!snapshot.enabled, "disabled snapshot records disabled state");
  Expect(!snapshot.attempted, "disabled registration does not call MMCSS");
  Expect(snapshot.task_name == "Pro Audio",
         "unknown task names normalize to Pro Audio");
  Expect(snapshot.priority == 2, "priority is clamped before recording");

  std::map<std::string, std::string> fields;
  aptt::AddAudioThreadMmcssBackendFields(fields, snapshot);
  Expect(fields["mmcss_enabled"] == "false", "fields include enabled flag");
  Expect(fields["mmcss_attempted"] == "false",
         "fields include attempted flag");
  Expect(fields["mmcss_task_name"] == "Pro Audio",
         "fields include normalized task name");
  Expect(fields["mmcss_priority_label"] == "Critical",
         "fields include priority label");
}

}  // namespace

int main() {
  TestPriorityLabelsClampToSupportedRange();
  TestDisabledRegistrationDoesNotTouchMmcss();
  std::cout << "audio thread scheduling tests passed\n";
  return 0;
}
