// SPDX-FileCopyrightText: 2024 LiveKit, Inc.
//
// SPDX-License-Identifier: Apache-2.0
import { realtime } from '@livekit/agents-plugin-openai';

const { RealtimeModel: OpenAIRealtimeModel } = realtime;
type OpenAIRealtimeModelOptions = ConstructorParameters<typeof OpenAIRealtimeModel>[0];

const XAI_BASE_URL = 'wss://api.x.ai/v1';
// Ref: python livekit-plugins/livekit-plugins-xai/livekit/plugins/xai/realtime/realtime_model.py - 32 lines
const DEFAULT_MODEL: GrokRealtimeModels = 'grok-voice-think-fast-1.0';
const DEFAULT_VOICE = 'ara';

const XAI_DEFAULT_TURN_DETECTION = {
  type: 'server_vad' as const,
  threshold: 0.5,
  prefix_padding_ms: 300,
  silence_duration_ms: 200,
  create_response: true,
  interrupt_response: true,
};

export type GrokVoices = 'eve' | 'ara' | 'rex' | 'sal' | 'leo';

// Ref: python livekit-plugins/livekit-plugins-xai/livekit/plugins/xai/types.py - 39-42 lines
export type GrokRealtimeModels = 'grok-voice-think-fast-1.0' | 'grok-voice-fast-1.0';

export interface RealtimeModelOptions extends Omit<OpenAIRealtimeModelOptions, 'model'> {
  model?: GrokRealtimeModels | string;
  voice?: GrokVoices | string;
  apiKey?: string;
}

export class RealtimeModel extends OpenAIRealtimeModel {
  override label(): string {
    return 'xai.RealtimeModel';
  }

  constructor(options: RealtimeModelOptions = {}) {
    super({
      baseURL: XAI_BASE_URL,
      model: DEFAULT_MODEL,
      voice: options.voice || DEFAULT_VOICE,
      apiKey: options.apiKey || process.env.XAI_API_KEY,
      modalities: ['audio', 'text'],
      turnDetection: XAI_DEFAULT_TURN_DETECTION,
      ...options,
    });
  }
}
