#!/usr/bin/env bun

/**
 * Basic functionality test for Buzz library
 * Tests device listing, player, recorder, and tone generation
 */

import Buzz from "./buzz"

console.log("🎵 Buzz Audio Library - Basic Test\n")

// Test 1: List devices
console.log("📋 Listing devices...")
const devices = await Buzz.listDevices()
console.log(`Found ${devices.length} device(s):`)
devices.forEach((d) => {
  console.log(`  ${d.type.padEnd(8)} ${d.label} (${d.id})`)
})
console.log("")

// Test 2: Create player
console.log("🔊 Creating default player...")
try {
  const player = await Buzz.player()
  console.log("✅ Player created\n")

  // Test 3: Play sound file
  console.log("🔊 Playing greeting sound...")
  const playback = await player.play("./sounds/greeting/greet1.wav")
  await playback.finished()
  console.log("✅ Sound played\n")

  // Test 4: Play tone
  console.log("🎵 Playing 440Hz tone for 1 second...")
  const tone = await player.playTone([440], 1000)
  await tone.finished()
  console.log("✅ Tone played\n")
} catch (error) {
  console.log(`⚠️  Skipping player tests: ${error instanceof Error ? error.message : error}\n`)
}

// Test 5: Create recorder
console.log("🎤 Creating default recorder...")
try {
  const recorder = await Buzz.recorder()
  console.log("✅ Recorder created\n")

  // Test 6: Stream recording with RMS
  console.log("📊 Recording for 2 seconds with RMS monitoring...")
  const recording = recorder.start()
  let chunkCount = 0
  let maxRMS = 0

  setTimeout(async () => {
    await recording.stop()
  }, 2000)

  for await (const chunk of recording.stream()) {
    chunkCount++
    const rms = Buzz.calculateRMS(chunk)
    if (rms > maxRMS) maxRMS = rms
    if (chunkCount % 20 === 0) {
      console.log(`  RMS: ${Math.round(rms)}`)
    }
  }

  console.log(`✅ Recorded ${chunkCount} chunks, max RMS: ${Math.round(maxRMS)}\n`)
} catch (error) {
  console.log(`⚠️  Skipping recorder tests: ${error instanceof Error ? error.message : error}\n`)
}

console.log("✅ All tests complete!")
