/**
 * Transcription provider factory.
 *
 * Creates a TranscriptionProvider based on STT_PROVIDER env var.
 * Auto-detects Azure vs OpenAI from available credentials if not explicit.
 *
 * Priority: STT_PROVIDER > auto-detect (AZURE_SPEECH_KEY → azure, OPENAI_API_KEY → openai)
 */

import { OpenAITranscriptionProvider } from './providers/openai.js';
import { AzureTranscriptionProvider } from './providers/azure.js';
import { MockTranscriptionProvider } from './providers/mock.js';
import type { TranscriptionProvider, STTProviderType } from './types.js';

let _provider: TranscriptionProvider | null = null;

/**
 * Resolve provider type from env vars.
 */
function resolveProviderType(): STTProviderType {
  const explicit = (process.env.STT_PROVIDER || '').toLowerCase();
  if (explicit === 'openai') return 'openai';
  if (explicit === 'azure') return 'azure';
  if (explicit === 'mock') return 'mock';

  // Auto-detect from available credentials
  if (process.env.AZURE_SPEECH_KEY && process.env.AZURE_SPEECH_REGION) return 'azure';
  if (process.env.OPENAI_API_KEY) return 'openai';

  return 'mock';
}

/**
 * Create a transcription provider by type.
 */
export function createSTTProvider(type: STTProviderType): TranscriptionProvider {
  switch (type) {
    case 'openai':
      return new OpenAITranscriptionProvider();
    case 'azure':
      return new AzureTranscriptionProvider();
    case 'mock':
      return new MockTranscriptionProvider();
    default:
      throw new Error(`Unknown STT_PROVIDER: '${type}'. Valid: openai, azure, mock`);
  }
}

/**
 * Get the singleton transcription provider.
 */
export function getSTT(): TranscriptionProvider {
  if (!_provider) {
    const type = resolveProviderType();
    _provider = createSTTProvider(type);
  }
  return _provider;
}

/**
 * Set the singleton transcription provider (for testing).
 */
export function setSTT(provider: TranscriptionProvider): void {
  _provider = provider;
}

/**
 * @internal Reset singleton (for testing).
 */
export function _resetSTT(): void {
  _provider = null;
}
