import { VideoWS } from '../ws.ts';
import path from 'node:path';
import net from 'net';
import { Recording } from '../../../../recorder/index.ts';
import Stream from 'stream';
import fs from 'node:fs'; // 新增

const recorder = new Recording({
  sampleRate: 16000,
  channels: 1, //
  audioType: 'wav',
  threshold: 0,
  recorder: 'rec',
  silence: '1.0',
  endOnSilence: true,
});
const writeFilePath = path.join(process.cwd(), 'funasr_test.wav');
const fileStream = fs.createWriteStream(writeFilePath, { encoding: 'binary' });

const url = 'wss://funasr.xiongxiao.me';
const url3 = 'wss://pro.xiongxiao.me:10095';
const url4 = 'wss://121.4.112.18:10095'; // aliyun
const url5 = 'https://1.15.101.247:10095'; // pro

const ws = new VideoWS({
  url: url5,
  isFile: false,
  // mode: 'online',
  mode: '2pass',
  wsOptions: {
    rejectUnauthorized: false,
  },
  onConnect: async () => {
    console.log('onConnect');
    ws.start();

    recorder.start();
    let len = 0;
    recorder.stream().on('data', (chunk) => {
      // ws.sendBuffer(chunk, { online: true });
      // console.log('Sending audio chunk:', chunk.length);
      ws.send(chunk)
      fileStream.write(chunk); // 新增：将音频数据写入文件
      len += chunk.length;
    });

    setTimeout(() => {
      ws.stop();
      fileStream.end(); // 新增：关闭文件流
      setTimeout(() => {
        process.exit(0);
      }, 1000);
      console.log('len', len);
    }, 10 * 1000);

    ws.emitter.on('message', (event) => {
      console.log('message', event.data);
    });
  },
});

const server = net.createServer((socket) => {
  socket.on('data', (data) => {
    console.log('data', data);
  });
});
server.listen(10097);
