type AliAsrServerOptions = {
  baseUrl?: string;
  appkey: string;
  token: string;
  format?: string;
  sampleRate?: string;
  enablePunctuationPrediction?: boolean;
  enableInverseTextNormalization?: boolean;
  enableVoiceDetection?: boolean;
};
export class AliAsrServer {
  private baseUrl: string;
  private appkey: string;
  private token: string;
  private format: string;
  private sampleRate: string;
  private enablePunctuationPrediction: boolean;
  private enableInverseTextNormalization: boolean;
  private enableVoiceDetection: boolean;

  constructor(opts?: AliAsrServerOptions) {
    const {
      baseUrl = 'https://nls-gateway-cn-shanghai.aliyuncs.com/stream/v1/asr',
      appkey = '',
      token = '',
      format,
      sampleRate,
      enablePunctuationPrediction = true,
      enableInverseTextNormalization = true,
      enableVoiceDetection = false,
    } = opts || {};
    this.baseUrl = baseUrl;
    this.appkey = appkey;
    this.token = token;
    this.format = format;
    this.sampleRate = sampleRate;
    this.enablePunctuationPrediction = enablePunctuationPrediction;
    this.enableInverseTextNormalization = enableInverseTextNormalization;
    this.enableVoiceDetection = enableVoiceDetection;
  }

  buildRequestUrl(): string {
    const params = new URLSearchParams();
    params.append('appkey', this.appkey);
    this.format && params.append('format', this.format);
    this.sampleRate && params.append('sample_rate', this.sampleRate);

    if (this.enablePunctuationPrediction) {
      params.append('enable_punctuation_prediction', 'true');
    }

    if (this.enableInverseTextNormalization) {
      params.append('enable_inverse_text_normalization', 'true');
    }

    if (this.enableVoiceDetection) {
      params.append('enable_voice_detection', 'true');
    }

    return `${this.baseUrl}?${params.toString()}`;
  }

  async processAudio(audioContent: Buffer): Promise<any> {
    try {
      // 设置请求头
      const headers = {
        'X-NLS-Token': this.token,
        'Content-Type': 'application/octet-stream',
      };

      // 构建请求URL
      const requestUrl = this.buildRequestUrl();

      // 发送请求
      const response = await fetch(requestUrl, {
        method: 'POST',
        headers,
        // @ts-ignore
        body: audioContent,
      });

      // 处理响应
      if (!response.ok) {
        console.log(`The audio file recognized failed, http code: ${response.status}`);
        const v = await response.text();
        console.log('The audio file recognized response:', v);
        return null;
      }
      // 解析响应体
      // console.log('The audio file recognized response:', v);
      const body = await response.json();

      if (body.status === 20000000) {
        console.log('The audio file recognized result:');
        console.log(body);
        console.log('result: ' + body.result);
        console.log('The audio file recognized succeed!');
        return body;
      } else {
        console.log('The audio file recognized failed!');
        console.log(body);
        return null;
      }
    } catch (error) {
      if (error.code === 'ENOENT') {
        console.log('The audio file does not exist!');
      } else {
        console.log('Error during audio processing:', error);
      }
      return null;
    }
  }
}

// // 使用示例
// async function main() {
//   const asrServer = new AliAsrServer({
//     appkey: '填入appkey',
//     token: '填入服务鉴权Token',
//     format: 'pcm',
//     sampleRate: '16000',
//     enablePunctuationPrediction: true,
//     enableInverseTextNormalization: true,
//     enableVoiceDetection: false,
//   });

//   const audioFile = '/path/to/nls-sample-16k.wav';
//   await asrServer.processAudio(audioFile);
// }

// // 执行主函数
// main().catch(console.error);
