const fs = require('fs');
const path = require('path');
const vm = require('vm');
const assert = require('node:assert/strict');
const ts = require('typescript');

const source = fs.readFileSync(path.join(__dirname, '../harmony/voice/src/main/ets/VoiceTurboModule.ets'), 'utf8');
const compiled = ts.transpileModule(source, {compilerOptions: {module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2020}}).outputText;

function createFixture() {
  const events = [], calls = [], capturers = [];
  let listener, granted = true, failStart = false;
  const engine = {
    setListener(value) { listener = value; },
    startListening({sessionId}) {
      calls.push(['start', sessionId]);
      queueMicrotask(() => failStart ? listener.onError(sessionId, 99, 'start failed') : listener.onStart(sessionId, ''));
    },
    cancel(id) { calls.push(['cancel', id]); },
    finish(id) { calls.push(['finish', id]); },
    shutdown() { calls.push(['shutdown']); },
    writeAudio(id) { calls.push(['write', id]); },
  };
  const audio = {
    AudioSamplingRate:{SAMPLE_RATE_16000:16000}, AudioChannel:{CHANNEL_1:1},
    AudioSampleFormat:{SAMPLE_FORMAT_S16LE:1}, AudioEncodingType:{ENCODING_TYPE_RAW:0},
    SourceType:{SOURCE_TYPE_VOICE_RECOGNITION:1},
    async createAudioCapturer() {
      const index = capturers.length;
      const capturer = {
        on(name, callback) { this.frame = callback; },
        async start() { calls.push(['record', index]); },
        async stop() { calls.push(['stop', index]); },
        async release() { await new Promise(r => setImmediate(r)); calls.push(['release', index]); },
      };
      capturers.push(capturer);
      return capturer;
    },
  };
  const exports = {};
  vm.runInNewContext(compiled, {exports, require(name) {
    if (name.includes('react-native-openharmony')) return {UITurboModule:class {}};
    if (name === '@kit.CoreSpeechKit') return {speechRecognizer:{async createEngine(){return engine;}}};
    if (name === '@kit.AudioKit') return {audio};
    if (name === '@kit.AbilityKit') return {abilityAccessCtrl:{createAtManager(){return {
      async requestPermissionsFromUser(){return {authResults:[granted ? 0 : -1]};},
    };}}};
    throw new Error(name);
  }, canIUse:()=>true, setTimeout, clearTimeout, console, Error, Uint8Array, Int16Array});
  const voice = new exports.VoiceTurboModule({rnInstance:{emitDeviceEvent:(name,payload)=>events.push({name,payload})}});
  return {voice, events, calls, capturers, get listener(){return listener;},
    deny(){granted=false;}, fail(){failStart=true;}};
}

(async () => {
  const f = createFixture();
  await Promise.all([f.voice.startSpeech('',{}), f.voice.startSpeech('',{}), f.voice.startSpeech('',{})]);
  assert.equal(await f.voice.isRecognizing(),true);
  assert.equal(f.calls.filter(c=>c[0]==='start').length,3);
  assert.equal(new Set(f.calls.filter(c=>c[0]==='start').map(c=>c[1])).size,3);
  for (let i=0;i<2;i++) {
    assert(f.calls.findIndex(c=>c[0]==='release' && c[1]===i) < f.calls.findIndex(c=>c[0]==='record' && c[1]===i+1));
  }
  const old = f.calls.find(c=>c[0]==='start')[1];
  const before = f.events.length;
  f.listener.onError(old, 99, 'stale');
  f.listener.onComplete(old, 'stale');
  f.listener.onResult(old, {result:'stale',isFinal:true,isLast:true});
  f.capturers[0].frame(new ArrayBuffer(640));
  assert.equal(f.events.length,before);
  assert.equal(await f.voice.isRecognizing(),true);
  assert.equal(f.calls.filter(c=>c[0]==='write').length,0);
  await f.voice.stopSpeech();
  assert.equal(await f.voice.isRecognizing(),false);
  await f.voice.startSpeech('',{});
  await f.voice.cancelSpeech();
  await f.voice.destroySpeech();
  assert.equal(await f.voice.isRecognizing(),false);

  const denied = createFixture(); denied.deny();
  await assert.rejects(denied.voice.startSpeech('',{}), /ohos.permission.MICROPHONE denied/);
  assert.equal(denied.events[0].payload.error.code,'permission');
  assert.equal(denied.capturers.length,0);
  assert.equal(await denied.voice.isRecognizing(),false);

  const failure = createFixture(); failure.fail();
  await assert.rejects(failure.voice.startSpeech('',{}), /start failed/);
  assert.equal(failure.events.filter(e=>e.name==='onSpeechError').length,1);
  assert.equal(failure.calls.filter(c=>c[0]==='record').length,0);
  assert.equal(failure.calls.filter(c=>c[0]==='release').length,1);
  console.log('PASS: concurrent restart, unique sessions, awaited audio release, stale callbacks/audio, stop/cancel/destroy, permission rejection, start failure cleanup. Mocked platform test; not device evidence.');
})().catch(error=>{console.error(error);process.exitCode=1;});