// Copyright (c) 2026 Tencent. All rights reserved.
// VoiceAI SDK Interface

import { Context } from '@ohos.abilityAccessCtrl';
import * as LiteavBase from '../liteav_base/liteav_module_entry';
import LiteAVSDKNative from 'libliteavsdk_voiceai.so';

/// 转录消息
export interface TXRealtimeASRMessage {
  segmentId: string;
  sourceText: string;
  isCompleted: boolean;
  speakerId: number;
}

/// 启动参数
export interface TXRealtimeASRParams {
  sdkAppId: string;
  userSig: string;
  voiceId: string;
  sourceLanguage: string;
  enableCustomCapture: boolean;
}

export interface TXRealtimeASRListener {
  onRealtimeASRStarted?: (voiceId: string) => void;
  onReceiveRealtimeASRMessage?: (message: TXRealtimeASRMessage) => void;
  onRealtimeASRStopped?: () => void;
  onRealtimeASRError?: (errorCode: number, errorMsg: string) => void;
}

/// TXRealtimeASR: ArkTS 公共 API
export class TXRealtimeASR {
  private nativeInstance: any;
  private listeners: TXRealtimeASRListener[] = [];

  constructor() {
    LiteavBase.initialize(null);
    this.nativeInstance = new LiteAVSDKNative.TXRealtimeASRNapi();

    // 设置内部回调代理, fan-out 到所有 listener
    this.nativeInstance.setListener({
      onRealtimeASRStarted: (voiceId: string) => {
        this.listeners.forEach(l => l.onRealtimeASRStarted?.(voiceId));
      },
      onReceiveRealtimeASRMessage: (message: TXRealtimeASRMessage) => {
        this.listeners.forEach(l => l.onReceiveRealtimeASRMessage?.(message));
      },
      onRealtimeASRStopped: () => {
        this.listeners.forEach(l => l.onRealtimeASRStopped?.());
      },
      onRealtimeASRError: (errorCode: number, errorMsg: string) => {
        this.listeners.forEach(l => l.onRealtimeASRError?.(errorCode, errorMsg));
      }
    });
  }

  addListener(listener: TXRealtimeASRListener): void {
    this.listeners.push(listener);
  }

  removeListener(listener: TXRealtimeASRListener): void {
    const idx = this.listeners.indexOf(listener);
    if (idx >= 0) {
      this.listeners.splice(idx, 1);
    }
  }

  startRealtimeASR(params: TXRealtimeASRParams): void {
    this.nativeInstance.startRealtimeASR(params);
  }

  stopRealtimeASR(): void {
    this.nativeInstance.stopRealtimeASR();
  }

  feedPcmData(data: ArrayBuffer, sampleRate: number, channels: number): void {
    this.nativeInstance.feedPcmData(data, sampleRate, channels);
  }

  callExperimentalAPI(json: string): string {
    return this.nativeInstance.callExperimentalAPI(json);
  }
}
