import vosk from 'vosk';
import { Recording } from '../../recorder/index.ts';
import fs from 'fs';
import path from 'path';
import { audioPath, sleep, mySpeechText } from './common.ts';
import { encodeWav, decodeWav } from '../../utils/convert.ts';
// 需要先下载Vosk模型
// const MODEL_PATH = 'vosk-model-small-en-us-0.15';
const MODEL_PATH = path.join(process.cwd(), 'models/vosk-model-small-cn-0.22');

async function detectWithVosk(audioFilePath) {
  if (!fs.existsSync(MODEL_PATH)) {
    console.error('请先下载Vosk模型');
    return false;
  }

  const model = new vosk.Model(MODEL_PATH);
  const rec = new vosk.Recognizer({ model: model, sampleRate: 16000 });

  // const wakeWords = ['hey computer', 'okay jarvis']; // 自定义唤醒词列表
  const wakeWords = ['欢迎']; // 自定义唤醒词列表
  const audioBuffer = fs.readFileSync(audioFilePath);
  const pcmBuffer = decodeWav(audioBuffer);
  const result = rec.acceptWaveform(pcmBuffer);
  console.log('result', result, rec.result());

  // const result = await rec.acceptWaveformAsync(pcmBuffer);
  // console.log('result', result, rec.result());

  // return new Promise((resolve) => {
  //   const pcmBufferLength = Buffer.byteLength(pcmBuffer);
  //   console.log('pcmBufferLength', pcmBufferLength);
  //   const bufferLength = 1024 * 8;
  //   let index = 0;
  //   for (let i = 0; i < pcmBufferLength; i += bufferLength) {
  //     const chunk = pcmBuffer.subarray(i, i + bufferLength);
  //     index++;
  //     if (rec.acceptWaveform(chunk)) {
  //       const result = rec.result();
  //       console.log('=========result', result, index);
  //       const text = result.text.toLowerCase();
  //       if (wakeWords.some((word) => text.includes(word))) {
  //         resolve(true);
  //       }
  //     }
  //   }
  //   resolve(false);
  // });
}

// detectWithVosk(audioPath).then((result) => {
//   console.log('result', result);
// });

detectWithVosk(mySpeechText).then((result) => {
  console.log('result', result);
});
