import fs from 'fs';
import path from 'path';

const publicLibsDir = path.resolve(import.meta.dirname, '../public/libs/ext');

if (!fs.existsSync(publicLibsDir)) {
  fs.mkdirSync(publicLibsDir, { recursive: true });
}

// Map of source paths to copy -> destination file name or directory
const libsToCopy = {
  'node_modules/occt-import-js/dist/occt-import-js.js': 'occt-import-js.js',
  'node_modules/occt-import-js/dist/occt-import-js-worker.js': 'occt-import-js-worker.js',
  'node_modules/occt-import-js/dist/occt-import-js.wasm': 'occt-import-js.wasm',
  
  'node_modules/rhino3dm/rhino3dm.min.js': 'rhino3dm.min.js',
  'node_modules/rhino3dm/rhino3dm.wasm': 'rhino3dm.wasm',

  'node_modules/web-ifc/web-ifc-api-iife.js': 'web-ifc-api-iife.js',
  'node_modules/web-ifc/web-ifc.wasm': 'web-ifc.wasm',

  'node_modules/draco3d/draco_decoder_nodejs.js': 'draco_decoder_nodejs.js',
  'node_modules/draco3d/draco_decoder.wasm': 'draco_decoder.wasm'
};

// online-3d-viewer actually expects 'draco_decoder_nodejs.min.js' but the npm package might not have it or it's different.
// Actually let's just copy everything exactly as they requested.

for (const [srcRel, destName] of Object.entries(libsToCopy)) {
  const src = path.resolve(import.meta.dirname, '..', srcRel);
  const dest = path.join(publicLibsDir, destName);
  
  if (fs.existsSync(src)) {
    fs.copyFileSync(src, dest);
    console.log(`Copied ${srcRel}`);
  } else {
    console.warn(`Missing source: ${srcRel}`);
  }
}

// Now let's patch online-3d-viewer
const o3dvFiles = [
  'node_modules/online-3d-viewer/build/engine/o3dv.module.js',
  'node_modules/online-3d-viewer/build/engine/o3dv.min.js',
  'node_modules/online-3d-viewer/build/engine/o3dv.js'
];

o3dvFiles.forEach(file => {
  const filePath = path.resolve(import.meta.dirname, '..', file);
  if (fs.existsSync(filePath)) {
    let content = fs.readFileSync(filePath, 'utf8');
    
    // Replace the URL for occt
    content = content.replace(/['"]https:\/\/[^'"]+occt-import-js[0-9\.@]*\/dist\/['"]/g, "'/libs/ext/'");
    content = content.replace(/occt-import-js\.worker\.js/g, 'occt-import-js-worker.js');
    
    // Replace the URL for rhino3dm
    content = content.replace(/['"]https:\/\/[^'"]+rhino3dm@[0-9\.]+\/rhino3dm\.min\.js['"]/g, "'/libs/ext/rhino3dm.min.js'");
    
    // Replace the URL for web-ifc
    content = content.replace(/['"]https:\/\/[^'"]+web-ifc@[0-9\.]+\/web-ifc-api-iife\.js['"]/g, "'/libs/ext/web-ifc-api-iife.js'");
    
    // Replace the URL for draco3d
    content = content.replace(/['"]https:\/\/[^'"]+draco3d@[0-9\.]+\/draco_decoder_nodejs\.min\.js['"]/g, "'/libs/ext/draco_decoder_nodejs.js'");

    fs.writeFileSync(filePath, content);
    console.log('Patched ' + file + ' for OFFLINE usage');
  }
});
