use nihility_listener::vad::{VoiceActivityDetection, VoiceActivityDetectionConfig};
use tracing::debug;

#[tokio::test]
async fn test_vad() -> Result<(), Box<dyn std::error::Error>> {
    nihility_log::init().expect("Failed to initialize logger");
    std::fs::create_dir_all("tests/.outputs")?;

    let (sample_sender, sample_receiver) = tokio::sync::broadcast::channel::<f32>(16000 * 1000 * 20);

    let mut reader = hound::WavReader::open("tests/samples/test.wav")?;
    let spec = reader.spec();
    debug!("Spec: {:?}", &spec);

    let vad_config = nihility_config::get_config::<VoiceActivityDetectionConfig>("nihility-vad")?;
    let mut vad = VoiceActivityDetection::init(vad_config, sample_receiver)?;

    for sample in reader.samples::<i16>().flatten() {
        sample_sender
            .send(f32::from(sample) / i16::MAX as f32)
            .expect("Failed to send sample");
    }
    drop(sample_sender);
    debug!("Waiting for a sample receiver");
    let mut speech_receiver = vad.get_speech_receiver();
    vad.run().await?;
    drop(vad);
    debug!("Vad done!");
    let mut index = 0;
    while let Ok(speech) = speech_receiver.recv().await {
        debug!("Vad got a speech, len: {}", speech.len());
        index += 1;
        let filename = format!("tests/.outputs/chunk_stream.{index}.wav");
        let mut file = hound::WavWriter::create(filename, spec)?;
        for sample in speech {
            file.write_sample((sample * 32768.0) as i16)?;
        }
    }
    debug!("Save done!");

    Ok(())
}
