// Node.js 22.23+ on your server. Install ws@8.21.3 and download hume-native-streams.mjs beside this file.
// Set ORUK_API_KEY and a saved ORUK_REQUEST_ID UUID. Run: node realtime-phrase-emotions.mjs recording.pcm
// Input: raw mono PCM16LE, 16,000 Hz, no WAV header. Output contains private transcripts/scores.
import {createReadStream} from 'node:fs'
import {stat} from 'node:fs/promises'
import {streamRealtime, MigrationStreamError} from './hume-native-streams.mjs'

const stop = new AbortController()
const interrupted = () => stop.abort()
process.once('SIGINT', interrupted)
try {
  const file = process.argv[2]
  if (!file) throw new Error('missing_input')
  const info = await stat(file)
  if (!info.isFile() || !info.size || info.size % 2 || info.size > 19_200_000) throw new Error('invalid_input')
  await streamRealtime({
    apiKey: process.env.ORUK_API_KEY,
    requestId: process.env.ORUK_REQUEST_ID,
    signal: stop.signal,
    source: signal => createReadStream(file, {highWaterMark: 10240, signal}),
    onEvent: event => {
      if (['conversation.item.input_audio_transcription.completed',
        'conversation.item.input_audio_emotion.completed',
        'conversation.item.input_audio_emotion.failed', 'session.usage'].includes(event.type)) {
        console.log(JSON.stringify(event))
      }
    },
  })
  // Success requires final transcript, usage AND clean close. No automatic reconnect/retry.
} catch (error) {
  console.error(JSON.stringify(error instanceof MigrationStreamError
    ? {code: error.code, requestId: error.requestId, mayHaveBeenBilled: error.mayHaveBeenBilled, action: error.action}
    : {code: 'setup_failed', action: 'Check the permitted PCM file and required environment.'}))
  process.exitCode = 1
} finally {
  process.removeListener('SIGINT', interrupted)
}
