// Classic Worker for FFmpeg - uses importScripts to load UMD core
// Avoids Vite module worker bundling issues entirely

let ffmpeg = null;

self.onmessage = async (e) => {
  const { id, type, data } = e.data;

  try {
    if (type === 'LOAD') {
      // data: { coreURL, wasmURL }
      const { coreURL, wasmURL } = data;

      // importScripts works in classic workers - loads UMD core synchronously
      importScripts(coreURL);

      // createFFmpegCore is set by the UMD script
      if (!self.createFFmpegCore) {
        self.postMessage({ id, type: 'ERROR', data: 'createFFmpegCore not found after importScripts' });
        return;
      }

      // Emscripten locateFile hack: encode wasmURL in the URL hash
      const mainScriptUrlOrBlob = coreURL + '#' + btoa(JSON.stringify({ wasmURL }));

      ffmpeg = await self.createFFmpegCore({
        mainScriptUrlOrBlob,
      });

      // Set up log and progress callbacks
      ffmpeg.setLogger((logData) => {
        self.postMessage({ type: 'LOG', data: logData });
      });
      ffmpeg.setProgress((progressData) => {
        self.postMessage({ type: 'PROGRESS', data: progressData });
      });

      self.postMessage({ id, type: 'LOAD', data: true });
      return;
    }

    if (!ffmpeg) {
      self.postMessage({ id, type: 'ERROR', data: 'ffmpeg not loaded' });
      return;
    }

    switch (type) {
      case 'WRITE_FILE': {
        // data: { path, data }
        ffmpeg.FS.writeFile(data.path, data.data);
        self.postMessage({ id, type: 'WRITE_FILE', data: true });
        break;
      }
      case 'READ_FILE': {
        // data: { path, encoding }
        const result = ffmpeg.FS.readFile(data.path, { encoding: data.encoding || 'binary' });
        const trans = [];
        if (result instanceof Uint8Array) trans.push(result.buffer);
        self.postMessage({ id, type: 'READ_FILE', data: result }, trans);
        break;
      }
      case 'DELETE_FILE': {
        ffmpeg.FS.unlink(data.path);
        self.postMessage({ id, type: 'DELETE_FILE', data: true });
        break;
      }
      case 'EXEC': {
        // data: { args, timeout }
        ffmpeg.setTimeout(data.timeout ?? -1);
        ffmpeg.exec(...data.args);
        const ret = ffmpeg.ret;
        ffmpeg.reset();
        self.postMessage({ id, type: 'EXEC', data: ret });
        break;
      }
      default:
        self.postMessage({ id, type: 'ERROR', data: 'unknown message type: ' + type });
    }
  } catch (err) {
    self.postMessage({ id, type: 'ERROR', data: (err && err.message) ? err.message : String(err) });
  }
};
