import path from 'path';
import tools from '@eui/tools/scripts/utils/tools.js'

(async function() {
  console.log('----------------------------------------------');
  console.log('Init package symlink...');
  console.log('----------------------------------------------');
  
  const nmSrcPath = path.join(process.cwd(), 'node_modules');
  const euiNmToolsPath = path.join(nmSrcPath, '@eui', 'automation');
  const eUIToolsPath = path.join(process.cwd(), 'packages', 'eui-automation');
  
  if (!tools.isDirExists(eUIToolsPath)) {
    console.error('Source directory does not exist:', eUIToolsPath);
    return;
  }
  
  return Promise.resolve()
    .then(() => {
      // Remove existing symlink or directory
      if (tools.isDirExists(euiNmToolsPath)) {
        console.log('Removing existing directory:', euiNmToolsPath);
        return tools.rimraf(euiNmToolsPath);
      }
    })
    .then(() => {
      // Ensure @eui directory exists
      const euiDir = path.join(nmSrcPath, '@eui');
      if (!tools.isDirExists(euiDir)) {
        console.log('Creating @eui directory:', euiDir);
        return tools.mkdirRecursive(euiDir);
      }
    })
    .then(() => {
      // Create symlink
      console.log('Creating symlink from', eUIToolsPath, 'to', euiNmToolsPath);
      return tools.link(eUIToolsPath, euiNmToolsPath);
    })
    .then(() => {
      console.log('----------------------------------------------');
      console.log('Repository ready to go!');
      console.log('----------------------------------------------');
    })
    .catch((e) => {
      console.error('ERROR initiating repository');
      console.error(e);
      process.exit(1);
    });
})();
